The introduction

When WordPress is used, the query and display of categories such as category and tag and articles are all carried out by WP_query query in PHP files specified by classification, and the results are displayed.

If you want to query a category or tag that is not fixed, but is displayed as the user page interacts, you need to use the POST request, which is mainly divided into two parts:

  1. Sends the POST request to theadmin-ajax.php
  2. In the themefunctions.phpThe hook function is used to process the passed argument and return the result

Configure the POST request in the template file

  • Add the following Script fragment to the corresponding PHP page template:
// javascript <script> <? php $admin_url=admin_url( 'admin-ajax.php' ); ? > $(document).ready(function($){var data={action:'postQuery', data: 'to pass data'} $.post("<? php echo $admin_url; ? >", data, function(response) { if(! response){ return; }else{ $("#tagRes").html(response); // Display the returned result in the page ID}}); }); </script>Copy the code
  • Pay attention tojsIn the POST requestAction: postQueryFor the callback hook functionpostQueryThe name of the function

functions.phpconfiguration

// functions.php function postQuery(){ $data = $_POST['data']; Echo $data; wp_reset_query(); die(); } add_action('wp_ajax_postQuery', 'postQuery'); add_action('wp_ajax_nopriv_postQuery', 'postQuery');Copy the code

perform

Perform the above method through interface click and other interactive operations and view it on the console:

This completes a post request for the page to WordPress.

Reference article:

  • How do I use Ajax in WordPress
  • Awhitepixel.com/blog/wordpr…
  • query_posts
  • WordPress article query usage complete