wp/wordpress文章页面添加阅读量/点击量,后台并显示阅读量

wordpress默认不带阅读量的,现在加上。在function.php加入代码

1、前端加入阅读量和点击量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//增加文章阅读次数
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;
}

  在线显示的地方,例如singe.php页面加入:

 <?php post_views('','次');?>
2、后台的管理页面,加上阅读量
复制代码
//在后台文章列表增加一列数据
add_filter( 'manage_posts_columns', 'customer_posts_columns' );
function customer_posts_columns( $columns ) {
$columns['views'] = '浏览次数';
return $columns;
}

//输出浏览次数
add_action('manage_posts_custom_column', 'customer_columns_value', 10, 2);
function customer_columns_value($column, $post_id){
if($column=='views'){
$count = get_post_meta($post_id, 'views', true);
if(!$count){
$count = 0;
}
echo $count;
}
return;
}

文章如果根据阅读量排序,可以
复制代码
 1 $hot_args = array(  
 2     'cat' => $hot_category_id, // 使用分类ID 
 3     'posts_per_page' => 6, // 获取所有文章  
 4     'ignore_sticky_posts' => 1, // 忽略置顶文章  
 5     'has_post_thumbnail' => true, // 只获取带有特色图片的文章  
 6     'meta_key' => 'views',
 7     'orderby' => 'meta_value',
 8 
 9     'order' => 'DESC' // 倒序排列  
10 ); 
复制代码
就是排序条件
 6     'meta_key' => 'views',
 7     'orderby' => 'meta_value',
 
复制代码

 

posted @   郑州谷多软件  阅读(306)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示