Search code examples
wordpressloopscategoriesshortcode

Limit posts to current category in shortcode


I have a custom shortcode to be used on archive pages and list the first 3 posts. But how do I limit the posts displayed to the current category without hardcoding categories?

This is working, but shows posts from all categories.

function archive_loop_shortcode() {
$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 3,
);

$my_query = null;
$my_query = new WP_query($args);
if($my_query->have_posts()):
    while($my_query->have_posts()) : $my_query->the_post();
        $custom = get_post_custom( get_the_ID() );
    echo "<div>".get_the_post_thumbnail()."</div>";
        echo "<h3>".get_the_title()."</h3>";
    endwhile;
    wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
endif;
}

add_shortcode( 'archive_loop', 'archive_loop_shortcode' );

Solution

  • Hope this code helps,

    function archive_loop_shortcode() {
        $current_cat = get_queried_object();
        
        $args = array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => 3,
            'tax_query'      => array(
                array(
                    'taxonomy' => $current_cat->taxonomy,
                    'field'    => 'term_id',
                    'terms'    => $current_cat->term_id,
                ),
            ),
        );
        
        $my_query = null;
        $my_query = new WP_query( $args );
        if ( $my_query->have_posts() ):
            while ( $my_query->have_posts() ) : $my_query->the_post();
                $custom = get_post_custom( get_the_ID() );
                echo "<div>" . get_the_post_thumbnail() . "</div>";
                echo "<h3>" . get_the_title() . "</h3>";
            endwhile;
            wp_reset_postdata();
        else :
            _e( 'Sorry, no posts matched your criteria.' );
        endif;
    }
    
    add_shortcode( 'archive_loop', 'archive_loop_shortcode' );