💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
以下是上述讨论中的所有示例代码段,汇编成两个完整的代码页:一个用于jQuery,另一个用于PHP。 ## PHP 此代码驻留在您的一个插件页面上。 ``` <?php add_action('admin_enqueue_scripts', 'my_enqueue'); function my_enqueue($hook) { if( 'myplugin_settings.php' != $hook) return; wp_enqueue_script( 'ajax-script', plugins_url( '/js/myjquery.js', __FILE__ ), array('jquery') ); $title_nonce = wp_create_nonce('title_example'); wp_localize_script('ajax-script', 'my_ajax_obj', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => $title_nonce, )); } add_action('wp_ajax_my_tag_count', 'my_ajax_handler'); function my_ajax_handler() { check_ajax_referer('title_example'); update_user_meta( get_current_user_id(), 'title_preference', $_POST['title']); $args = array( 'tag' => $_POST['title'], ); $the_query = new WP_Query( $args ); echo $_POST['title'].' ('.$the_query->post_count.') '; wp_die(); // all ajax handlers should die when finished } ``` ##查询 此代码位于您的插件文件夹下面的文件js/myjquery.js中。 ``` jQuery(document).ready(function($) { //wrapper $(".pref").change(function() { //event var this2 = this; //use in callback $.post(my_ajax_obj.ajax_url, { //POST request _ajax_nonce: my_ajax_obj.nonce, //nonce action: "my_tag_count", //action title: this.value //data }, function(data) { //callback this2.nextSibling.remove(); //remove the current title $(this2).after(data); //insert server response }); }); }); ``` 在存储首选项之后,将所得的帖子计数添加到所选标题。 ## 更多信息 - How To Use AJAX In WordPress - AJAX for WordPress