以下是前面讨论中的所有示例代码片段,组装成两个完整的代码页:一个用于jQuery,另一个用于PHP。
此代码位于您的一个插件页面上。
add_action(“admin_enqueue_scripts”,“my_enqueue”);函数my_enqueue($hook){if('myplugin_settings.php'!==$hook){回报;}wp_排队_脚本(“ajax-script”,plugins_url('/js/myjquery.js',__FILE__),数组(“jquery”),'1.0.0',真的);$title_nonce=wp_create_nonce(“title_example”);wp_localize_script(“ajax-script”,“my_ajax_obj”,阵列(“ajax_url”=>admin_url(“admin-ajax.php”),“nonce”=>$title_nonce,));}add_action('wp_ajax_my_tag_count','my_ajax_handler');函数my_ajax_handler(){check_ajax_referer(“标题示例”);$title=wp_unslash($_POST['title']);更新用户元数据(get_current_user_id(),'title_preference',$title);$args=数组(“tag”=>$title,);$the_query=新WP_query($args);echo esc_html($title)。'('.$the_query->post_count.')';wp_die();//所有ajax处理程序都应该在完成时终止}
此代码在文件中js/myjquery.js
在插件文件夹下面。
jQuery(document).ready(function($){//包装器$(“.pref”).change(function(){//eventvar this2=这个;//在回调中使用$.post(my_ajax_obj.ajax_url,{//post请求_ajax_nonce:my_ajax_obj.nonce,//nonce操作:“my_tag_count”,//操作标题:this.value//数据},函数(数据){//回调this2.nextSibling.remove()//删除当前标题$(this2).after(data);//插入服务器响应});});});
存储首选项后,生成的帖子计数将添加到所选标题。