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

I’m using a modified version of Twenty Twelve and I’m trying to display recent posts from the same category as the current post (except the current post) in the sidebar.

I started this way but something’s not ok:

    $category = get_the_category($post->ID); 
    $current_cat = $category[0]->cat_name; //This will get me the first category assigned to the current post but since every post has only ONE cat. assigned to, it's good enough
   //Next, in my sidebar widget I have this:
    $my_query = new WP_Query('category_name=".$current_cat."&showposts=10');
    while ($my_query->have_posts()) : $my_query->the_post();
    ...display my titles here ...
    unset($current_cat); //I'm not sure I need to unset this variable?
    endwhile;

I’m not really a programmer so I’m struggling with understanding the logic but I’d like to learn.
Any suggestions/help much appreciated!

Thank you,
Alex

2 Answers
2

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