iTranslated by AI
3 Ways to Display a List of Posts in WordPress
Lists of articles and static pages can be retrieved using new WP_Query() or get_posts(). However, since their usage differs slightly, I'll note down the equivalent ways to write them. The following three examples all yield the same output.
i = 1, title1
i = 2, title2
i = 3, title3
found = 3
WP_Query() and while loop
WP_Query() returns an object, so you use new. It is used in combination with a while loop. Thanks to this $query->the_post(), you can use functions such as get_the_title() and get_field("name");. I have included $found = $query->post_count; to retrieve the number of posts and $i++ to count the sequence, but these can be removed if not needed.
<?php
$query = new WP_Query([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'order' => 'desc',
'orderby' => 'date'
]);
$found = $query->post_count;
$i = 0;
if ($query->have_posts()) : while ($query->have_posts()) : $i++; $query->the_post();
?>
<p>i = <?php echo $i;?>, <?php echo get_the_title();?></p>
<?php endwhile; endif; ?>
<p>found = <?php echo $found?></p>
get_posts() and foreach loop
get_posts() returns an array, so new is not required. It is used in combination with foreach or for loops. setup_postdata($post) is required as the equivalent statement to $query->the_post(). Without this, functions like get_the_title() cannot be used. Use count() to retrieve the number of posts.
<?php
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'order' => 'desc',
'orderby' => 'date'
]);
$found = count($posts);
$i = 0;
foreach ($posts as $post) : $i++; setup_postdata($post);
?>
<p>i = <?php echo $i;?>, <?php echo get_the_title();?></p>
<?php endforeach; ?>
<p>found = <?php echo $found?></p>
get_posts() and for loop
Similar to the foreach loop, setup_postdata($post) is required. Also, please note that PHP array indices are zero-based. Since it's an array, elements are retrieved as $post=$posts[$i].
<?php
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'order' => 'desc',
'orderby' => 'date'
]);
$found = count($posts);
for ($i=0; $i<$found; $i++) : $post=$posts[$i]; setup_postdata($post);
?>
<p>i = <?php echo $i+1;?>, <?php echo get_the_title();?></p>
<?php endfor; ?>
<p>found = <?php echo $found?></p>
Summary
To use functions such as get_the_title() or get_field("name");:
-
new WP_Query()requires$query->the_post() -
get_posts()requiressetup_postdata($post)
Discussion