How do I create a shortcode in wordpress that displays recent posts?
Asked on Sep 03, 2025
Answer
Creating a shortcode in WordPress to display recent posts involves using a custom function and the `add_shortcode` hook. This allows you to insert the shortcode anywhere in your posts or pages to dynamically show recent posts.
<!-- BEGIN COPY / PASTE -->
function recent_posts_shortcode($atts) {
$atts = shortcode_atts(
array(
'number' => 5, // Default number of posts
),
$atts,
'recent-posts'
);
$query = new WP_Query(array(
'posts_per_page' => $atts['number'],
'post_status' => 'publish',
));
$output = '<ul>';
while ($query->have_posts()) : $query->the_post();
$output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
$output .= '</ul>';
wp_reset_postdata();
return $output;
}
add_shortcode('recent-posts', 'recent_posts_shortcode');
<!-- END COPY / PASTE -->Additional Comment:
- Add this code to your theme's `functions.php` file or a custom plugin.
- Use the shortcode `[recent-posts]` in your posts or pages to display the list.
- You can specify the number of posts by using `[recent-posts number="3"]`.
- Ensure that your theme supports shortcodes in the desired content area.
Recommended Links: