Display recent posts from the same category as current post in sidebar

Try this

        // Get categories
        $categories = wp_get_post_terms( get_the_ID(), 'category');

        // Check if there are any categories
        if( ! empty( $categories ) ) :

            // Get all posts within current category, but exclude current post
            $category_posts = new WP_Query( array(
                'cat'          => $categories[0]->term_id,
                'post__not_in' => array( get_the_ID() ),
            ) );

            // Check if there are any posts
            if( $category_posts->have_posts() ) :
                // Loop trough them
                while( $category_posts->have_posts() ) : $category_posts->the_post();
                    // Display posts
                    echo get_the_title() . '<br />';
                endwhile;
            endif;
        endif;

Also, check out this page for more information about WP_Query for looping through posts, and don’t forget to reset the postdata using wp_reset_postdata();

Leave a Comment