在single.php中有以下代码:
if ( is_single() ){
global $post;
$count_post = esc_attr( get_post_meta( $post->ID, '_post_views_count', true) );
if( $count_post == ''){
$count_post = 1;
add_post_meta( $post->ID, '_post_views_count', $count_post);
}else{
$count_post = (int)$count_post + 1;
update_post_meta( $post->ID, '_post_views_count', $count_post);
}
}
在my_content.php中,此代码显示视图:
<?php global $post;
$visitor_count = get_post_meta( $post->ID, '_post_views_count', true);
if( $visitor_count == '' ){ $visitor_count = 0; }
if( $visitor_count >= 1000 ){
$visitor_count = round( ($visitor_count/1000), 2 );
$visitor_count = $visitor_count.'k';
} ?>
<p class="meta_do">
<b class="icon-eye"></b>
<?php echo esc_attr($visitor_count); ?> views
</p>
对于登录的用户,一切都很好,但是问题在于,它不计算未登录用户的浏览量(或刷新)。
我对代码进行了一些优化,以使其更短,更易读
if ( is_single() ) {
global $post;
$count_post = (int)esc_attr( get_post_meta( $post->ID, '_post_views_count', true ) );
update_post_meta( $post->ID, '_post_views_count', ++$count_post );
}
my_content.php:
<?php
global $post;
$visitor_count = (int)get_post_meta( $post->ID, '_post_views_count', true );
if ( $visitor_count >= 1000 ) {
$visitor_count = round( ( $visitor_count / 1000 ), 2 );
$visitor_count = $visitor_count . 'k';
}
?>
<p class="meta_do">
<b class="icon-eye"></b>
<?php echo esc_attr( $visitor_count ); ?> views
</p>