Querying Posts Using AJAX In WordPress Returns All Posts

May 22nd, 2014 - Posted by Steve Marks to Javascript / jQuery, PHP, Web Development.

I’ve found myself doing a lot of work recently with AJAX requests in WordPress. Today was no different when I was tasked with implementing an infinite scroll onto a blog. The user would scroll and the next set of posts would be pulled in when the user reached the bottom.

Initially I got this set up relatively quickly by using the following code in my theme’s functions.php file:

function wp_infinitepaginate()
{
    $paged           = $_POST['page_no'];
    $postType        = $_POST['post_type'];
    
    $blog_query = new WP_Query( 'post_type='.$postType.'&paged=' . $paged );
                        
    if ( $blog_query->have_posts() ) : 
                
        while ( $blog_query->have_posts() ) : 
                                
            $blog_query->the_post();
                    
            get_template_part( 'blog-post' );
                    
        endwhile;
        
    endif;
                                
    // Reset Post Data
    wp_reset_postdata();
    
    exit;
}
add_action('wp_ajax_infinite_scroll', 'wp_infinitepaginate'); // for logged in user
add_action('wp_ajax_nopriv_infinite_scroll', 'wp_infinitepaginate'); // if user not logged in

This seemed to work initially, but after a while I started to notice that non-published posts were being pulled in by the AJAX request.

The Solution

After looking at the WordPress Codex for WP_Query I noticed the following extract:

And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are ‘future’, ‘draft’ and ‘pending’.

That would certainly explain why I was getting pending and draft posts. A quick change to my WP_Query like so….

$blog_query = new WP_Query( 'post_type='.$postType.'&post_status=publish&paged=' . $paged );

… and the infinite scroll then began to only return published posts as you’d expect.

This entry was posted on Thursday, May 22nd, 2014 at 10:10 am by +Steve Marks and is filed under Javascript / jQuery, PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first