这是一篇来自另一个OP没有发现有用的问题的重新调整用途的帖子,所以我将它转载在这里,希望在这里有用
请根据需要修改代码。
这是我最近在stackoverflow上写的一篇帖子。它是您正在使用的代码的修改版本。我对那个代码也有同样的问题。
这是我用来在网站中显示帖子视图的代码。请注意,管理员视图不计算在内,如果有人在12小时内访问同一帖子,则第二个视图不计算在内。仅当该用户在12小时后再次访问该页面时,才会注册第二次查看计数。所以这是一种更准确的统计帖子浏览量的方法
if ( ! function_exists( \'pietergoosen_get_post_views\' ) ) :
function pietergoosen_get_post_views($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 0;
}
return $count;
}
endif;
// function to count views.
if ( ! function_exists( \'pietergoosen_update_post_views\' ) ) :
function pietergoosen_update_post_views($postID) {
if( !current_user_can(\'administrator\') ) {
$user_ip = $_SERVER[\'REMOTE_ADDR\']; //retrieve the current IP address of the visitor
$key = $user_ip . \'x\' . $postID; //combine post ID & IP to form unique key
$value = array($user_ip, $postID); // store post ID & IP as separate values (see note)
$visited = get_transient($key); //get transient and store in variable
//check to see if the Post ID/IP ($key) address is currently stored as a transient
if ( false === ( $visited ) ) {
//store the unique key, Post ID & IP address for 12 hours if it does not exist
set_transient( $key, $value, 60*60*12 );
// now run post views function
$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);
}
}
}
}
endif;
remove_action( \'wp_head\', \'adjacent_posts_rel_link_wp_head\', 10, 0);
现在只需在需要显示计数的地方添加以下代码
<div class="readercount">
<?php $views = pietergoosen_get_post_views(get_the_ID());
if(pietergoosen_get_post_views(get_the_ID()) == 1) {
printf( __( \'%d Reader have read this post.\', \'pietergoosen\' ) , $views );
} else {
printf( __( \'%d Readers have read this post.\', \'pietergoosen\' ) , $views );
}
?>
</div>
并在single中添加以下代码。php注册计数
pietergoosen_update_post_views(get_the_ID());