0

I'm trying to fetch posts in ajax. Everything is working but It is showing only one post. Please check my code and tell me if something is wrong

function ag_get_posts() {
    global $post;
    $args = array(
      'post_type' => 'post',
      'posts_per_page' => 12,
      'post_status' => 'publish',
    );

query_posts( $args );


while ( have_posts() ) : the_post(); 
locate_template( 'post.php', TRUE, TRUE );
 endwhile;

wp_reset_query();
    exit;
}

add_action('wp_ajax_ag_get_posts', 'ag_get_posts');

jQuery:

var data = {
    action: 'ag_get_posts',
};

jQuery.post(AjaxPath.ajaxurl, data, function(response) {
var result = $(response)
    Content.html(result);
});

1 Answer 1

1

If you read the documentation for locate_template you'll see the problem.

locate_template( $template_names, $load, $require_once );

$require_once (boolean) (optional) If true, the template file will be loaded with the php require_once function. If false, the template file will be loaded with the php require function. This parameter has no effect if $load is false. Default: true

PHP won't load your template more than once because you've set $require_once to true.

A simpler API function for this purpose is get_template_part:

get_template_part( 'post' );
2
  • But get_template_part doesn't work in functions.php. This function is made for template files only. I just set $require_once to FALSE, now its working. :)
    – wp student
    Commented Mar 29, 2014 at 18:34
  • Just checked, get_template_part(); also worked. Thanks for the tip.
    – wp student
    Commented Mar 29, 2014 at 18:44

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.