如果你想实时跟踪你的 WordPress 文章浏览/被用户点击数,又不想用插件的话,那么你可以使用下面的这些代码,下面的代码片段将为你的每篇文章提供统计数据。
一、找到你的主题functions.php php文件,然后添加以下代码:
function getCrunchifyPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "暂时无人阅读";
}
return $count.' 人已阅读';
}
function setCrunchifyPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
二、将这个代码片段放在主题循环内 single.php 文件中,注意尽量往前面靠点,或者放到你想要让它出现的位置:
<?php setCrunchifyPostViews(get_the_ID()); ?>
<?php echo getCrunchifyPostViews(get_the_ID()); ?>
比如我就放在正文顶部的位置,最后更新下你的php文件基本上就可以了。当然了,以上我们已经完成了在我们的数据库中存储每个帖子的视图计数的过程。但是有的小伙伴还想在后台的仪表板的后置屏幕上显示文章的浏览数,怎么办?继续往下看。
首先,我们需要添加一个自定义列,在 functions.php 文件中使用以下代码,我们将”Post Views”列添加到文章列表页面中:
add_filter('manage_post_posts_columns', function ( $columns )
{
if( is_array( $columns ) && ! isset( $columns['post_views'] ) )
$columns['post_views'] = __( 'Post Views' );
return $columns;
} );
接下来,在每篇文章的”文章列表”栏下显示视图计数,放置下面的代码:
add_action( 'manage_post_posts_custom_column', function ( $column_name, $post_id )
{
if ( $column_name == 'post_views') {
$post_view_count = get_post_meta($post_id, 'views_count', true);
$count = $post_view_count ? $post_view_count : 0;
echo $count;
}
}, 10, 2 );
所以我们的最终functions.php代码如下:
function count_post_views() {
if (is_single()) {
global $post;
$post_id = $post->ID;
$count = 1;
$post_view_count = get_post_meta($post_id, 'views_count', true);
if ($post_view_count) {
$count = $post_view_count + 1;
}
update_post_meta($post_id, 'views_count', $count);
}
}
add_action('wp_head', 'count_post_views');
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
/*Add custom column on post listing table*/
add_filter('manage_post_posts_columns', function ( $columns )
{
if( is_array( $columns ) && ! isset( $columns['post_views'] ) )
$columns['post_views'] = __( 'Post Views' );
return $columns;
} );
/*Display views count under the custom columns*/
add_action( 'manage_post_posts_custom_column', function ( $column_name, $post_id )
{
if ( $column_name == 'post_views') {
$post_view_count = get_post_meta($post_id, 'views_count', true);
$count = $post_view_count ? $post_view_count : 0;
echo $count;
}
}, 10, 2 );
效果:
版权声明:
本网站的所有文字、图片资料,均由作者亲自整理创作,任何媒体、网站或个人未经本网协议授权不得复制、转载、转贴或以其他方式复制发布/发表,请尊重我的劳动成果,侵权必究,谢谢。