1

I am using ajax with wordpress. But while querying through ajax into function i am getting only one post.

here is my code :

 $args = array(
    'post_type'       => 'post',
    'posts_per_page'  => -1,
    'order'           => 'DESC',
  );

$posts = new WP_Query($args);
  if($posts->have_posts()){
    while ($posts->have_posts()) {
      $posts->the_post();
        $output = get_the_title();
    }
  }wp_reset_postdata();

  wp_send_json( $output );

In console log im getting lastpost title only :(

1 Answer 1

1

You are resetting the $output value in the loop. Declare an empty variable first, and then append each result to it in the loop:

  if($posts->have_posts()){
    $output = '';
    while ($posts->have_posts()) {
      $posts->the_post();
        $output .= get_the_title();
    }
  }

This will add all the posts to the $output variable.

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.