WordPress如何按浏览量排序获取当前分类下的Top5文章
WordPress获取当前分类下按浏览量排序前5篇文章的实现方法
前置说明
WordPress核心默认不自带文章浏览量统计功能,需要先添加自定义字段记录浏览量,再基于该字段查询排序。如果已经使用了浏览量统计插件,可跳过第一步,直接替换对应自定义字段名即可。
第一步:添加浏览量统计代码
将以下代码添加到当前使用主题的functions.php文件中:
// 统计文章浏览量 function record_post_views() { global $post; $post_id = $post->ID; // 排除管理员、预览场景,避免重复统计 if (is_preview() || current_user_can('manage_options')) return; $count_key = 'post_views_count'; $count = get_post_meta($post_id, $count_key, true); if ($count == '') { $count = 0; delete_post_meta($post_id, $count_key); add_post_meta($post_id, $count_key, '0'); } else { $count++; update_post_meta($post_id, $count_key, $count); } } add_action('wp_head', 'record_post_views');
第二步:添加分类页文章查询代码
在分类页模板(通常是category.php)需要展示热门文章的位置,添加以下代码:
if (is_category()) { // 获取当前分类ID $current_cat = get_queried_object_id(); // 配置查询参数 $popular_posts_args = array( 'cat' => $current_cat, 'posts_per_page' => 5, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'post_status' => 'publish' ); $popular_posts = new WP_Query($popular_posts_args); // 循环输出文章 if ($popular_posts->have_posts()) { echo '<ul class="cat-popular-posts">'; while ($popular_posts->have_posts()) { $popular_posts->the_post(); echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a> <span class="views">(浏览量:'.get_post_meta(get_the_ID(), 'post_views_count', true).')</span></li>'; } echo '</ul>'; } // 重置查询,避免影响页面主循环 wp_reset_postdata(); }
注意事项
- 编辑主题文件前建议先备份,避免语法错误导致站点无法访问
- 若使用子主题,建议将代码添加到子主题的
functions.php和对应模板文件中,避免主主题更新后代码被覆盖 - 若已使用WP-PostViews等浏览量统计插件,将上述代码中的自定义字段名
post_views_count替换为插件对应字段即可(WP-PostViews对应字段为views)
内容的提问来源于stack exchange,提问作者Tarunpreet Singh
相关产品推荐
相关产品推荐

