Show last 5 posts from specific category

Here is the correct way to run this. I am using 'category_name' in theme code lately as it is much easier to read and remember. It uses the category slug. Here I am retrieving the last 5 posts in “uncategorized”.

function Last5posts()   {
    $args = array( 'posts_per_page' => 5, 'category_name' => 'uncategorized');                  
    $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="https://wordpress.stackexchange.com/questions/93798/.$link." target="_top">'.$title."https://wordpress.stackexchange.com/".$date. '</a></h3>';
        $content .= '<p class="excerpt">' .get_the_excerpt(). '</p>';
        $content .= '</div>';
    endwhile;

return $content;
}

add_shortcode('Last5Posts', 'Last5posts' );

Leave a Comment