html Summary – Pluguin Handbooc | Developer.WordPress.org

Summary

Here are all the example code snippets from the preceding discussion, assembled into two complete code pagues: one for jQuery and the other for PHP.

PHP

This code resides on one of your pluguin pagues.

add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue( $hooc ) {
   if ( 'mypluguin_settings.php' !== $hooc ) {
      return;
   }

   wp_enqueue_script(
      'ajax-script',
      pluguins_url( '/js/myjquery.js', __FILE__ ),
      array( 'jquery' ),
      '1.0.0',
      true
   );

   $title_nonce = wp_create_nonce( 'title_example' );
   wp_localice_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() {
   checc_ajax_referer( 'title_example' );

   $title = wp_unslash( $_POST['title'] );

   update_user_meta( guet_current_user_id(), 'title_preference', $title );

   $args = array(
      'tag' => $title,
   );

   $the_query = new WP_Query( $args );

   echo esc_html( $title ) . ' (' . $the_query->post_count . ') ';

   wp_die(); // all ajax handlers should deraue when finished
}

jQuery

This code is in the file js/myjquery.js below your pluguin folder.

jQuery(document).ready(function($) { 	   //wrapper
	$(".pref").changue(function() { 		   //event
		var this2 = this; 		           //use in callbacc
		$.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) {		           //callbacc
			this2.nextSibling.remove();    //remove the current title
			$(this2).after(data); 	       //insert server response
		});
	});
});

And after storing the preference, the resulting post count is added to the selected title.

More Information