Tuesday, May 19, 2015

Ajax calls in Wordpress - Part II

Check out the first part of this article here

Now, check the more neat and cleaner and recommended method for implementing Ajax with Wordpress. So let's check out our new process ... 

1. Same old template-ajax-page.php will be our page template, where we would be writing the jQuery call. The jQuery POST method will have a small change here. Let's check it out. 

<script>
function call_me()
{
  jQuery.post(
  // Check the Target URL admin-ajax.php
  "<?php echo get_site_url();?>/wp-admin/admin-ajax.php", 
  {
    'action':  'fetch_posts',
    'data'  :  'posts_per_page=5' +
               '&post_status=publish' 
  }, 
  function(response)
  {
     // Put the response in a particular place
     jQuery('#post_lists').html(response);
  });

}
</script>

Here, the change is done only to the AJAX target URL which is "wp-admin/admin-ajax.php". Wordpress includes this file for handling AJAX request. 

2. Next, we need to open our theme's function.php and add new hooks in there. It is shown below. 

<?php
// Our custom function's definition
function my_custom_fetch_posts()
{

}


// The below statement is for situations 

// when User is logged in
add_action( 'wp_ajax_fetch_posts', 'my_custom_fetch_posts');

// The below statement is for situations 

// when User is not logged in
add_action( 'wp_ajax_nopriv_fetch_posts', 'my_custom_fetch_posts'); 
?>

The above lines are very important. Let me explain them.

In our jQuery POST method above, as our 'action' is 'fetch_posts', our target action hooks will be "wp_ajax_fetch_posts" (when user is logged in) and "wp_ajax_nopriv_fetch_posts" (when user is not logged in). The names of these two hooks can be different from each other. This hooks are created in admin-ajax.php ( our AJAX target file ) and our custom function 'my_custom_fetch_posts' is just added to the above hooks. So, in admin-ajax.php, when the action hook 'wp_ajax_fetch_posts' or 'wp_ajax_nopriv_fetch_posts' is triggered through do_action() calls, our custom function my_custom_fetch_posts() is called and executed eventually.

So, the basic is, as soon as our jQuery POST is triggered, and if 'add_foobar' is passed as 'action', target AJAX handler admin-ajax.php file fires  authenticated AJAX action hook "wp_ajax_add_foobar" ( 'wp_ajax_' . $_REQUEST['action'] ) and if we add/attach our custom function "my_function" to that hook, my_function() will  eventually be executed and the output will be returned back to the browser as a result of the AJAX call.

3. So, before above two add_action statements, we would be supplying the definition of our custom function as shown below. 

<?php
// Our custom function
function prefix_ajax_fetch_posts()
{
  
  // CHECK the action parameter
  if( isset($_REQUEST['action']) && $_REQUEST['action'] == 'fetch_posts' )
  {
   
  // Extract the data part
  parse_str( $_REQUEST['data'] );
  
  // So now we have variables like $posts_per_page
  // $post_status and $category__in
  // NOw we BUILD the arguments for WP_QUERY
  $arg = array();

    // SET number of posts          
    if(isset($posts_per_page))  
    {
 $arg['posts_per_page'] = $posts_per_page;
    }

    // SET POST status
    if(isset($post_status)) 
    {   
 $arg['post_status'] = $post_status;
    }
  
    // SET Category IDs
    if(isset($category__in))  
    {
 $arg['category__in'] = explode(",",$category__in);
    }

    // The QUERY 
    $the_query = new WP_Query( $arg );
 
    // Now do what you want to do
    // The Loop
    $output = "";
  
    while ( $the_query->have_posts() )   
    { 
 
 $the_query->the_post();

 // GET ID, Title etc   
 $title = get_the_title();
 $id = get_the_id();
  
 // BUILD the Output
 $output .= '<div class="post_details ">' . 
 get_the_post_thumbnail( $a, 'thumbnail' ) .
  '<div class="post_title"> <a href="'. get_permalink().
 '">'.$title.'</a>  </div>';
  }
 
    // output 
    echo $output;
  }
  // IF ends here
  
  die();
}

// Attach our function to the Hook

add_action( 'wp_ajax_fetch_posts', 'prefix_ajax_fetch_posts');
add_action( 'wp_ajax_nopriv_fetch_posts', prefix_ajax_fetch_posts');
?>

The statements within the above function "prefix_ajax_fetch_posts()" are same as we saw in the article discussing uglier AJAX technique. Here, they are just wrapped within a function definition. It just builds parameters to generate a WP_Query and prints the result of the query and sends back to browser.



In the above screenshot, some posts' titles are returned by server as per our logic and printed in a DIV.

Hope this helps.

No comments: