Proper way to display latest 5 posts grouped by post type?

i need to display the latest 5 posts of each post type, something like:

Latest BMW Posts:

Post title BMW 1
Post title BMW 2

Latest Audi Posts:

Post title Audi 1
Post title Audi 2

And so on.

It seems that https://codex.wordpress.org/Function_Reference/wp_get_recent_posts does it. Something like:

<h2>Latest BMW Posts:</h2>
<ul>
<?php
$args = array(
‘numberposts’ => 5,
‘post_type’ => ‘bmw’
);
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo ‘<li><a href=”‘ . get_permalink($recent[“ID”]) . ‘”>’ . $recent[“post_title”].'</a> </li> ‘;
}
wp_reset_query();
?>
</ul>

<h2>Latest Audi Posts:</h2>
<ul>
<?php
$args = array(
‘numberposts’ => 5,
‘post_type’ => ‘audi’
);
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo ‘<li><a href=”‘ . get_permalink($recent[“ID”]) . ‘”>’ . $recent[“post_title”].'</a> </li> ‘;
}
wp_reset_query();
?>
</ul>

The problem is: when you have 10 or more types it can get overwhelming.

Can the code be used with an array of post types and loop them to avoid repeating the same code for each type?
Is this really a light task or would it kill MySQL? If so what’s the most efficient way to get such output?

Read more here:: Proper way to display latest 5 posts grouped by post type?

Leave a Reply

Your email address will not be published. Required fields are marked *