WordPress get posts by category

How to create a shortcode to display all posts in a category WP.

function askiw_shortcode($attr, $content = null){
    global $post;
    // First Defining Shortcode's Attributes
    $shortcode_args = shortcode_atts(
                        array(
                                'cat'     => $attr,
                                'num'     => '6',
                                'order'  => 'desc'
                        ), $attr);
    //Array with query arguments
    $args = array(
                    'cat'              => $shortcode_args['cat'],
                    'posts_per_page' => $shortcode_args['num'],
                    'order'          => $shortcode_args['order'],
                 );
    $recent_posts = get_posts($args);
    $output = '<ul>';
    foreach ($recent_posts as $post) :  
        setup_postdata($post);
        $output .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';    
    endforeach;      
    wp_reset_postdata();
    $output .= '</ul>';  
    return $output;
}
 
add_shortcode( 'cat', 'askiw_shortcode' ); 

How to put a shortcode.

[cat id="3"  num="3000" order="asc"]

Leave a Reply