Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get wordpress main query posts as an array

Tags:

php

wordpress

I need to get the main query posts as an array. Example, in common tag page(tag.php), I need to get all the posts as an array ( like get_posts() do) and display it using some multiple loops instead of using default wordpress loop as shown under

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
like image 805
Manesh Avatar asked Mar 31 '26 06:03

Manesh


1 Answers

$posts is the variable you're looking for it. It is the equivalent of get_posts results for the main query. It's in the global namespace, so in order to access it somewhere else you'll need to use the keyword global.

global $posts;
foreach( $posts as $a_post ) {
    echo $a_post->post_title;
}
like image 161
C. E. Avatar answered Apr 02 '26 18:04

C. E.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!