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?
post_type
as an argument. 2. That depends. You'll have to make the queries somehow, it will probably be best to cache the result and invalidate the cached page if any of the post types contents' changes.car
and differentiating via a taxonomy? Doesn't really change anything for you for now, but in the future it will be alot easier. Also you can just query for that taxonomy and then get all of their posts