
您现在的位置是:首页 > WordPress教程WordPress教程
WordPress如何显示热门文章
WP集市
2025-09-01
【WordPress教程】
1432人已围观
-
想让WordPress站点显示热门文章?其实跟泡面一样简单,但别只会用插件——虽然那玩意像外卖方便,但自己搞更香。核心原理就是抓取文章被瞅的次数(post views),然后按这个数排序输出。咱先从不用插件的裸奔方式开始。
-
首先得让WordPress会数数——记录每篇文章被看了几次。把这段代码扔进主题的functions.php里,就像给电脑装个计数器:
function track_post_views($post_id) { if (is_single() && !is_user_logged_in()) { $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', 'track_post_views');
-
接着在需要显示热门文章的地方(比如侧边栏)直接调取数据。用WP_Query搞个循环,就像从冰箱里拿啤酒一样自然:
$popular_query = new WP_Query(array( 'posts_per_page' => 5, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' )); while ($popular_query->have_posts()) : $popular_query->the_post(); echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; endwhile; wp_reset_postdata();
-
要是嫌代码烫手?装个Jetpack或者Post Views Counter插件也行,但注意别让插件拖慢速度——就像吃太饱会犯困。插件设置里通常勾选“显示热门文章区块”,拖到小工具区就能用。
-
最后记得缓存热门查询!用transientAPI把结果存15分钟,避免每次访问都查数据库——跟泡茶时多泡几杯放着是一个道理:
$popular_posts = get_transient('popular_posts'); if (false === $popular_posts) { // 重新运行查询并设置 transient set_transient('popular_posts', $popular_posts, 15 * MINUTE_IN_SECONDS); }
-
现在你的站点就像夜市烤串摊——哪篇文章最香一目了然。不过别忘了,热门文章不等于优质内容,就像网红店不一定好吃,关键还是要有真材实料。
Tags:
文章版权声明:除非注明,否则均为WP集市原创文章,转载或复制请以超链接形式并注明出处。

热门文章
