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

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

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

//增加文章阅读次数
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 @ 2024-03-07 10:28  郑州谷多软件  阅读(146)  评论(0编辑  收藏  举报