Show last 5 posts from specific category (WordPress)

I’m trying to show the last 5 posts from a specific category, which will be linked to a function so I can insert the shortcode in a WordPress page. The code I have is as below, it does everything I need (although I want to add featured image too) except it does not show posts from a specific category.

I’ve tried numerous things, but cannot find a working fix.

Read More
function Last5posts()
{
    $args = array( "showposts" => 5, "category" => 3 ); 
    $content = "";   

    query_posts($args);

    if ( have_posts() ) : 

        while ( have_posts() ) :
            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>n";
            $content .= "<p class='excerpt'>" . get_the_excerpt() . "</p>";
            $content .= "</div>";

        endwhile;

        wp_reset_query(); 

     endif;

     return $content;
}

add_shortcode('Last5Posts', 'Last5posts' );   

I have tried replacing lines 3 and 4 with the code below, but it throws an error “syntax error, unexpected ‘}’ on line 31”.

$catquery = new WP_Query( 'cat=3&posts_per_page=10' );
while($catquery->have_posts()) : $catquery->the_post(); 

Any help would be greatly appreciated.

Related posts

Leave a Reply

3 comments

  1. you can use code just like below

    query_posts( 'cat=3&posts_per_page=5' );
    

    using this wordpress by default will use last 5 post after this code…

  2. Use this
    $catnames[1] denotes which category u want to use related to that post.

    <?php $catnames = get_the_category();  
    $postcatid=$catnames[1]->term_id;
    
    $catquery = new WP_Query( 'cat='.$postcatid.'&posts_per_page=4' );
    while($catquery->have_posts()) : $catquery->the_post();
    ?>
    <ul>
    <li><h3><a href="<?php the_permalink() ;?>" rel="bookmark"><?php the_title(); ?></a>    </h3>
    </li>
    </ul>
     <?php endwhile; 
    ?>