wp query - Get array of posts from the current archive page loop

admin2025-06-03  2

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?

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?

Share Improve this question edited Jan 30, 2019 at 16:58 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Jan 30, 2019 at 16:23 Marvin3Marvin3 6631 gold badge10 silver badges20 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 8

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

global $wp_query;
$my_posts = $wp_query->posts;
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748961113a315181.html

最新回复(0)