Create a Custom Shortcode to Display Recent Posts in WordPress

Johan S Jan 3, 2025 Shortcodes
How can I show my latest blog posts anywhere on my website?
How do I create a custom shortcode in WordPress to display a list of recent posts with specific attributes?
Andy answered Jan 3, 2025

Custom Shortcode Solution

Basic Implementation

Add this code to your theme's functions.php file or in a site-specific plugin:

This code creates a shortcode [recent_posts] with customizable attributes:

function display_recent_posts($atts) {
    $args = shortcode_atts(array(
        'posts' => 5,           // Number of posts to show
        'category' => '',       // Category slug
        'order' => 'DESC',      // Order of posts (DESC or ASC)
        'excerpt' => 'true',    // Show excerpt or not
        'thumbnail' => 'true'   // Show thumbnail or not
    ), $atts);

    $query = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => $args['posts'],
        'category_name' => $args['category'],
        'order' => $args['order']
    ));

    $output = '<div class="recent-posts-list">';
    
    while($query->have_posts()) : $query->the_post();
        $output .= '<div class="recent-post-item">';
        
        if($args['thumbnail'] === 'true' && has_post_thumbnail()) {
            $output .= '<div class="post-thumbnail">';
            $output .= get_the_post_thumbnail(get_the_ID(), 'thumbnail');
            $output .= '</div>';
        }
        
        $output .= '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
        
        if($args['excerpt'] === 'true') {
            $output .= '<div class="post-excerpt">' . get_the_excerpt() . '</div>';
        }
        
        $output .= '</div>';
    endwhile;
    
    wp_reset_postdata();
    $output .= '</div>';
    
    return $output;
}
add_shortcode('recent_posts', 'display_recent_posts');

Usage Examples

Use the shortcode in posts, pages, or widgets:

[recent_posts]
[recent_posts posts="3" category="news" excerpt="false"]
[recent_posts posts="4" thumbnail="false" order="ASC"]

Optional Styling

Add this CSS to your theme's stylesheet or Customizer:

.recent-posts-list {
    margin: 20px 0;
}

.recent-post-item {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
}

.post-thumbnail {
    margin-bottom: 10px;
}

.post-thumbnail img {
    max-width: 100%;
    height: auto;
}

Plugin Alternatives

If you prefer a plugin solution, consider these options:

  1. Display Posts Shortcode - Lightweight and flexible
  2. Recent Posts Widget Extended - Includes widgets and shortcodes
  3. Post Grid Elementor Addon - If using Elementor page builder

Additional Tips

  • The shortcode is responsive and works in any theme
  • Modify the CSS to match your theme's styling
  • Use the category slug (not name) in the shortcode
  • The code supports pagination through WP_Query parameters
  • Images use WordPress's built-in thumbnail size