wordpress侧栏添加推荐文章

本文最后更新于 2023年9月28日。

原文链接:http://caibaojian.com/wordpress-popular-view-posts.html

一个网站比较基本的元素,点击率就是比较常见的要求,通过文章点击的统计来分析网站哪些文章比较受欢迎,从而吸引用户注意到这部分优秀的文章。

WordPress默认是没有加入点击次数的,你可以通过添加一个插件叫post-view-plus等相关插件来使其支持输出点击次数、热门点击文章小工具等。本文介绍的是另外一种方式,通过添加一个自定义字段view到function.php中来实现点击次数统计和输出热门点击文章。

//Post View From caibaojian.com
function record_visitors(){
if (is_singular()) {global $post;
$post_ID = $post->ID;
if($post_ID)
{
$post_views = (int)get_post_meta($post_ID, 'views', true);
if(!update_post_meta($post_ID, 'views', ($post_views+1)))
{
add_post_meta($post_ID, 'views', 1, true);
}
}
}
}
add_action('wp_head', 'record_visitors');
function post_views($before = '(点击 ', $after = ' 次)', $echo = 1)
{
global $post;
$post_ID = $post->ID;
$views = (int)get_post_meta($post_ID, 'views', true);
if ($echo) echo $before, number_format($views), $after;
else return $views;
};

然后再需要显示访问次数的文章加上以下代码:·


在侧栏添加你的热门点击文章代码:

     5,//文章数 'meta_key' => 'views', 'orderby' => 'meta_value_num', 'date_query' => array( array( 'after' => '2 month ago',//时间范围 )) ); $postslist = get_posts( $args ); foreach ( $postslist as $post ) : setup_postdata( $post ); ?>
  • <a href="">

还有另外一个通过MySQL查询的函数。

//code from http://caibaojian.com/wordpress-popular-view-posts.html
/*
* 热门点击文章
*
“一个月内”文章点击排名:
文章点击排名:
*/
function get_mostviewed($limit = 5,$limitdays=30,$before = '
  • ', $after = '
  • ') { //Popular Post From caibaojian.com global $wpdb; if($limitdays==0||$limitdays=="") $where = ""; else $where .= " AND post_date > '" . date('Y-m-d', strtotime("-$limitdays days")) . "'"; $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' ".$where." AND post_type  'page' AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit"); if($most_viewed) { foreach ($most_viewed as $post) { global $post; $post_ID = $post->ID; $views = (int)get_post_meta($post_ID, 'views', true); //$post_views = (int)get_post_meta($post_ID, 'views', true); $post_title = htmlspecialchars(stripslashes($post->post_title)); $permalink = get_permalink($post->ID); echo $before ."$post_title  $views". $after; } } }



    来源:前端开发博客