I have a page that uses three queries to retrieve a variety of content. One of those queries grabs posts that are related to the topic of the page. Since these posts can be of all sorts and related through a variety of methods (various magic fields defined values, their category, etc.) I am using a custom query to grab them (something where I build some args and pass them to WP_Query() like so: $collected_child_posts = new WP_Query($args);

Currently I return 5 results at a time (in my args I have 'posts_per_page' => 5) and I want to page those results using ajax so that only that block of results updates when you click a MORE POSTS link.

I implemented this by adding a url to the MORE POSTS button that looks like ?paged=n and then having that retrieved via ajax. Problem is I get the entire page back (including the desired posts) when I only want the posts themselves.

Any ideas on the best way to retrieve just those posts from the subquery without returning the entire page?


1 Answer 1


Two options-

load a page fragment using jQuery's load method (see Loading Page Fragments),

or create your own ajax function to load posts and return it in whatever markup you wish:

add_action('wp_ajax_my_ajax_get_posts', 'my_ajax_callback');
add_action('wp_ajax_nopriv_my_ajax_get_posts', 'my_ajax_callback');
function my_ajax_callback() {
    $args = $_POST['myargs'];
    $collected_child_posts = new WP_Query($args);
    echo 'some stuff';

pass the admin-ajax url to your javascript via wp_localize_script, or put it directly in your template via admin_url('admin-ajax.php');

then call admin-ajax.php and pass your ajax action:

    $.post(your_ajaxurl, {
        action: 'my_ajax_get_posts',
        myargs: args
    function(data) {

the first method is obviously simpler, but the second is easier on the server since a lot less of WP is loaded to execute an ajax call this way, plus less data is getting sent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.