Hey folks! I’m stuck trying to set up a shortcode that shows the 5 most recent blog posts on my WordPress site. I’ve been messing around with it for a while but can’t seem to get it right. Anyone got any tips or tricks for this?
Here’s what I’ve come up with so far, but it’s not quite doing the job:
hey there! ur code looks pretty good already, but i got a small suggestion. try adding ‘orderby’ => ‘date’ and ‘order’ => ‘DESC’ to ur get_posts args. that’ll make sure u get the most recent posts. also, maybe add a read more link? just a thought. good luck with ur site!
Your approach is solid, but there’s room for improvement. I’d suggest incorporating error handling and caching to enhance performance. Here’s a refined version:
This version includes caching to reduce database queries and improve load times. It also handles the case where no posts are found. Remember to clear the cache when you publish new posts.
I’ve been through a similar situation, and I can share what worked for me. Your code is on the right track, but there are a few tweaks that can make it more robust and flexible:
Use WP_Query instead of get_posts for better performance and more options.
Add a permalink to each post title so users can click through.
Use get_the_excerpt() instead of wp_trim_words() for a more accurate summary.
Wrap the function in a check to ensure the shortcode isn’t already defined.
Here’s an improved version based on my experience:
if (!function_exists('recent_posts_display')) {
function recent_posts_display($atts) {
$atts = shortcode_atts(array('posts' => 5), $atts);
$query = new WP_Query(array('posts_per_page' => $atts['posts']));
$output = '<div class=\"recent-posts\">';
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$output .= '<article>';
$output .= '<h3><a href=\"' + get_permalink() + '\">' + get_the_title() + '</a></h3>';
$output .= '<p>' + get_the_excerpt() + '</p>';
$output .= '</article>';
}
}
wp_reset_postdata();
$output .= '</div>';
return $output;
}
add_shortcode('recent_posts', 'recent_posts_display');
}
This should give you a more flexible and efficient solution. Hope it helps!