Get array of posts from the current archive page loop

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?

1 Answer
1

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

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

Leave a Comment