用wp ajax创建在后台获取文章的小插件

Published
2023-08-24
浏览次数 :  43

php

<?php 
/**
 * Plugin Name: Wp learn rest api 
 * Description: Learn about rest api 
 * Author: WordPress
 * Version: 1.0
 */

/**
 * Create admin page to show form submission 
 */

add_action( 'admin_menu', 'wp_learn_rest_submenu' );

function wp_learn_rest_submenu() {

  add_menu_page( 
    'Wp Learn admin page', 
    'Wp Learn admin page', 
    'manage_options', 
    'wp_learn_admin', 
    'wp_learn_rest_render_option_page', 
    'dashicons-admin-tools' );

}


//render form submission admin page 

function wp_learn_rest_render_option_page() { ?>

  <div class="wrap" id="wp_learn_admin">
    <h1>Admin</h1>
    <button id="wp-learn-ajax-button">Load posts via admin ajax </button>
    <button id="wp-learn-rest-api-button">Load posts via Rest Api </button>
    <button id="wp-learn-clear-posts">Clear Posts </button>
    <h2>Posts</h2>
    <textarea id="wp-learn-posts" cols="125" rows="125"></textarea>
  </div>

  <?php 


}

//enqueue js scripts to make the request 
add_action( 'admin_enqueue_scripts', 'wp_learn_rest_enqueue_script' );

function wp_learn_rest_enqueue_script() {


  wp_enqueue_script('wp-learn-rest-api', plugin_dir_url( __FILE__ ) . 'wp-learn-rest-api.js',array('jquery'),time(),true);

  wp_localize_script( 'wp-learn-rest-api', 'wp_learn_ajax', array(
    'ajax_url'  => admin_url('admin-ajax.php')


  ) );
}

//handle the learn fetch posts ajax request  钩子是 wp_ajax_{action}
add_action( 'wp_ajax_learn_fetch_posts', 'wp_learn_ajax_fetch_posts' );

function wp_learn_ajax_fetch_posts() {


  $posts = get_posts(  );
  wp_send_json($posts);
  wp_die();  //all ajax handlers die when finished 
}

JS

jQuery(document).ready(($) => {
  const loadPostsButton = $("#wp-learn-ajax-button");

  if (loadPostsButton) {
    loadPostsButton.on('click',(e) => {
      $.post(
        wp_learn_ajax.ajax_url,
        {
          action:'learn_fetch_posts',
        },

        function (posts) {
          const textarea = $("#wp-learn-posts");
          posts.forEach(function(post) {
            textarea.append(post.post_title + '\n');
          });
        }

        )



    });


  }

});

/**
 * Clear the textarea button 
 */
const clearPostsButton = document.getElementById('wp-learn-clear-posts'); 

if (clearPostsButton) {

  clearPostsButton.addEventListener('click',function(){
    const textarea = document.getElementById('wp-learn-posts');
    textarea.value = ''


  });
}

  • 标签1
  • 标签1
  • 标签1
Top