根据帖子的类别显示侧栏中最近的帖子标题列表

时间:2013-12-18 03:10:28

标签: php wordpress post sidebar

我试图根据帖子所在的类别显示侧栏中的最新帖子标题。此代码适用于特定页面模板,但如果我将其放在single.php文件中,我只能从一个类别中提取帖子。

有没有办法根据帖子的类别显示帖子标题?

<!-- 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 -->   

1 个答案:

答案 0 :(得分:1)

首先获取可见帖子的类别,然后用该查询。

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

然后在您的查询中,

<?php 
    $my_query = new WP_Query( array( 
        'category__in' => $post_cat_ids, 
        'showposts' => 10 
    )); 
?>
相关问题