方法一:使用 get_posts()(推荐)
<?php
if ( is_single() ) :
global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
<li class="widget widget_recent_entries" id="category-<?php echo $category->term_id;?>-posts">
<h2 class="widgettitle"><?php echo $category->name; ?> 热门文章</h2>
<ul>
<?php
$popular_posts = get_posts(array(
'numberposts' => 5,
'category' => $category->term_id,
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
foreach($popular_posts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<span class="view-count">(<?php echo getPostViews(get_the_ID()); ?> 阅读)</span>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php
endforeach;
wp_reset_postdata();
endif;
?>
方法二:使用 WP_Query
<?php
if ( is_single() ) :
global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
<li class="widget widget_recent_entries" id="category-<?php echo $category->term_id;?>-posts">
<h2 class="widgettitle"><?php echo $category->name; ?> 热门文章</h2>
<ul>
<?php
$popular_query = new WP_Query(array(
'posts_per_page' => 5,
'cat' => $category->term_id,
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
if ($popular_query->have_posts()) :
while ($popular_query->have_posts()) : $popular_query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<span class="view-count">(<?php echo getPostViews(get_the_ID()); ?> 阅读)</span>
</li>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</ul>
</li>
<?php
endforeach;
endif;
?>
本文地址: WordPress文章页调用本分类热门文章
版权声明:如发现本站有涉嫌抄袭侵权/违法违规的内容请联系客服!




