Recent Posts from a Specific Category

3d Animation

I was struggling to display a list of recent posts from a specific category archive in WordPress. Thanks to this code from WP Engine, I was able to place a list of recent posts in a widget.

This is the code that needs to be added to your functions.php file. This sample code collects the last 5 posts from a specific archive permalink. If you only want a list of post titles and links you can simply remove the lines of $content that request the bits you don’t need.


function Last5posts()   {
    $args = array( 'posts_per_page' => 5, 'category_name' => 'your-category-permalink');                  
    $last_5_posts_query = new WP_Query( $args );
    while($last_5_posts_query->have_posts()) : 
        $last_5_posts_query->the_post();
        $link = get_permalink();
        $title = get_the_title();
        $date = get_the_date();                              

        $content .= '<div class="latest-posts">';
        $content .= '<h3><a href='.$link.' target="_top">'.$title.' / '.$date. '</a></h3>';
        $content .= '<p class="excerpt">' .get_the_excerpt(). '</p>';
        $content .= '</div>';
    endwhile;

return $content;
}

add_shortcode('Last5Posts', 'Last5posts' );

Once this code has been added to your functions.php you can then add the shortcode to a page or widget.


[Last5Posts]