Custom code for adding a shortcode to display recent posts

Bob C Dec 16, 2024 Shortcodes
How can I make a simple button that shows my latest blog posts?
How do I create a WordPress shortcode to output a list of recent posts with specific parameters?
Andy answered Dec 16, 2024

Here's a custom solution to create a shortcode that displays recent posts as a button list:

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

function recent_posts_button_shortcode($atts) {
    $args = shortcode_atts(array(
        'posts' => 5,
        'category' => '',
        'button_color' => '#0073aa',
        'text_color' => '#ffffff'
    ), $atts);

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

    $output = '<div class="recent-posts-buttons">';
    
    while ($query->have_posts()) {
        $query->the_post();
        $output .= sprintf(
            '<a href="%s" class="recent-post-button" style="background-color: %s; color: %s;">%s</a>',
            get_permalink(),
            esc_attr($args['button_color']),
            esc_attr($args['text_color']),
            get_the_title()
        );
    }
    
    $output .= '</div>';
    wp_reset_postdata();
    
    return $output;
}
add_shortcode('recent_posts_buttons', 'recent_posts_button_shortcode');

Add this CSS to your theme's stylesheet or in the WordPress Customizer's Additional CSS section:

.recent-posts-buttons {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.recent-post-button {
    display: inline-block;
    padding: 10px 20px;
    text-decoration: none;
    border-radius: 5px;
    transition: opacity 0.3s;
}

.recent-post-button:hover {
    opacity: 0.9;
}

Usage examples:

  • Basic usage: [recent_posts_buttons]
  • With parameters: [recent_posts_buttons posts="3" category="news" button_color="#FF0000" text_color="#FFFFFF"]

Parameters:

  • posts: Number of posts to display (default: 5)
  • category: Category slug to filter posts (default: all categories)
  • button_color: Background color of buttons (default: #0073aa)
  • text_color: Text color of buttons (default: #ffffff)

Alternative Plugin Solutions:

  1. Display Posts Shortcode - Offers more advanced display options and filtering
  2. Recent Posts Widget Extended - Provides both widget and shortcode functionality

The custom code solution provides a clean, lightweight approach with customizable buttons. It's mobile-responsive and can be styled further using CSS.