3

Classic WordPress loop (for example in archive.php) looks like this:

if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        get_template_part( 'template-parts/content', get_post_format() );
    endwhile;
endif;

I want to get an array of post objects on archive page without having to do this:

$my_posts = array();
while ( have_posts() ) {
  the_post();
  $my_posts[] = $post;
}

// $my_posts is array of post objects

Is there any simpler method to get it?

4

That’s pretty easy. All you need is this:

global $wp_query;
$my_posts = $wp_query->posts;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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