I have created an action with the below function and I can display the number of views of each post But every time the page is refreshed, one view is added to this I want the actual number of views of the post to be displayed Thank you for your guidance
/* Counter PostViews*/
function set_post_view_custom_field() {
if ( is_single() ) {
global $post;
$post_id = $post->ID;
$count = 1;
$post_view_count = get_post_meta( $post_id, 'post_view_count', true );
if ( $post_view_count ) {
$count = $post_view_count 1;
}
update_post_meta( $post_id, 'post_view_count', $count );
}
}
add_action( 'wp_head', 'wpb_track_post_views');
CodePudding user response:
You can do this using cookies. Basically set a cookie that has a lifetime of 1 hour, so that when refreshing the page, if the cookie exists, it means the user has already been on this article in the last hour :
function set_post_view_custom_field() {
if ( is_single() ) {
global $post;
$post_id = $post->ID;
$count = 1;
if ( !isset( $COOKIE['post_view_count' . $post_id] ) ) {
$post_view_count = get_post_meta( $post_id, 'post_view_count', true );
if ( $post_view_count ) {
$count = $post_view_count 1;
}
update_post_meta( $post_id, 'post_view_count', $count );
setcookie( 'post_view_count_' . $post_id, $post_id, time() 3600 );
}
}
}
add_action( 'wp_head', 'wpb_track_post_views');