WordPress怎么设置热门文章,详细教程

来自:素雅营销研究院

头像 方知笔记
2025年05月05日 19:34

一、为什么需要设置热门文章功能

在WordPress网站中设置热门文章功能对于提升用户体验和网站流量有着重要作用。热门文章能够:

  • 向访客展示最受欢迎的内容
  • 增加页面停留时间
  • 提高文章曝光率
  • 促进内容传播
  • 提升SEO效果

二、使用插件设置热门文章

1. 安装并激活热门文章插件

推荐使用以下插件:

  • WordPress Popular Posts(最受欢迎)
  • Post Views Counter
  • Top 10

以WordPress Popular Posts为例:

  1. 进入WordPress后台 → 插件 → 安装插件
  2. 搜索”WordPress Popular Posts”
  3. 点击”立即安装”然后”激活”

2. 配置插件设置

激活后:

  1. 进入”设置” → “WordPress Popular Posts”
  2. 在”数据”选项卡设置统计方式(按浏览次数、评论数等)
  3. 在”显示”选项卡设置显示样式(列表、缩略图等)
  4. 保存设置

3. 添加热门文章小工具

  1. 进入”外观” → “小工具”
  2. 找到”WordPress Popular Posts”小工具
  3. 拖拽到侧边栏或其他小工具区域
  4. 配置显示参数(文章数量、时间范围等)
  5. 保存设置

三、不使用插件的代码实现方法

1. 通过文章浏览量统计

在主题的functions.php文件中添加以下代码:

// 记录文章浏览数
function set_post_views() {
if (is_single()) {
$post_id = get_the_ID();
$count = get_post_meta($post_id, 'post_views_count', true);
if ($count == '') {
$count = 0;
delete_post_meta($post_id, 'post_views_count');
add_post_meta($post_id, 'post_views_count', '0');
} else {
$count++;
update_post_meta($post_id, 'post_views_count', $count);
}
}
}
add_action('wp_head', 'set_post_views');

// 获取文章浏览数
function get_post_views($post_id) {
$count = get_post_meta($post_id, 'post_views_count', true);
if ($count == '') {
delete_post_meta($post_id, 'post_views_count');
add_post_meta($post_id, 'post_views_count', '0');
return "0";
}
return $count;
}

2. 创建热门文章查询

在需要显示热门文章的位置添加:

$popular_posts = new WP_Query(array(
'posts_per_page' => 5,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));

if ($popular_posts->have_posts()) :
while ($popular_posts->have_posts()) : $popular_posts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;
endif;
wp_reset_postdata();

四、优化热门文章显示效果

1. 添加缩略图显示

// 在查询中添加缩略图支持
if (has_post_thumbnail()) {
the_post_thumbnail('thumbnail');
}

2. 添加浏览次数显示

echo '浏览: ' . get_post_views(get_the_ID()) . '次';

3. 添加时间范围限制

修改查询参数,只显示特定时间范围内的热门文章:

$popular_posts = new WP_Query(array(
'posts_per_page' => 5,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array(
array(
'after' => '1 month ago'
)
)
));

五、热门文章功能的SEO优化建议

  1. 避免重复内容:确保热门文章模块不会在多个页面重复相同内容
  2. 合理放置位置:侧边栏、文章底部或专门的热门文章页面
  3. 添加结构化数据:使用Schema标记增强搜索引擎理解
  4. 移动端适配:确保在移动设备上显示良好
  5. 加载速度优化:考虑使用缓存或延迟加载技术

六、常见问题解答

Q:热门文章数据不准确怎么办? A:检查统计代码是否正确安装,清除缓存后重新测试。

Q:如何重置热门文章统计? A:使用插件的话可以在设置中找到重置选项;代码实现需要手动删除post_views_count元数据。

Q:热门文章会影响网站速度吗? A:合理配置影响很小,可以考虑使用缓存或限制查询数量。

Q:能否按分类显示热门文章? A:可以,在查询参数中添加’category_name’或’cat’参数即可。

通过以上方法,你可以轻松在WordPress网站上实现热门文章功能,无论是使用插件还是自定义代码都能满足不同需求。根据网站实际情况选择最适合的方案,定期检查并优化热门文章的显示效果,将有助于提升网站的用户体验和内容传播效果。