Question

I am trying to show the most recent posts titles in the sidebar based on what category the post resides in. This code works great for a specific page template, but if I put this in the single.php file, I can only pull post titles from one category.

Is there a way to show post titles based on the category of the post?

<!-- BEGIN SIDEBAR -->

<div class="col-md-4 column blogsidebar">
<aside id="recent-posts-4" class="widget widget_recent_entries">        
<h1 class="widget-title">Recent Articles</h1><hr>   
<?php $my_query = new WP_Query('category_name=Blog&showposts=10'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); echo '<br>'; ?>
<a href="<?php the_permalink() ?>" rel="bookmark">
<?php the_title(); ?></a><br>
<?php echo word_count(get_the_excerpt(), '12'); ?>...<br>
<?php endwhile; ?><p></p>
</div>

<!-- END SIDEBAR -->   
Was it helpful?

Solution

First get the category of the visible post, and then query with that.

$post_cat_ids = wp_get_object_terms( get_the_ID(), 'category', array('fields' => 'ids'));

Then on your query,

<?php 
    $my_query = new WP_Query( array( 
        'category__in' => $post_cat_ids, 
        'showposts' => 10 
    )); 
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top