WordPress article reading statistics implementation ideas:
Every time you enter the article details page, the cookie will be used to determine whether the user has visited the article within the set expiration time. If not, the number of views will be increased by one.
The implementation process is as follows:
1. Add the following code to the theme’s functions.php file and place it at the bottom of the file:
function getPostViews($postID){ $count_key = 'views'; $count = get_post_meta($postID, $count_key, true); if($count=='' || !$count){ return "0"; } return $count; } function setPostViews($postID){ $count_key = 'views'; $count = get_post_meta($postID, $count_key, true); if($count=='' || !$count) { $count = 1; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, $count); }else{ $count++; update_post_meta($postID, $count_key, $count); } }
2. Add the following code to the single.php file of the theme. The time interval can be customized and placed at the top of the file:
<?php if(!isset($_COOKIE['views'.$post->ID.COOKIEHASH]) || $_COOKIE['views'.$post->ID.COOKIEHASH] != '1'){ setPostViews($post->ID); setcookie('views'.$post->ID.COOKIEHASH,'1',time() + 99999999,COOKIEPATH,COOKIE_DOMAIN); } ?>
3. Add the following code to the location where you want to display the number of views , such as article list (template-parts/content.php), article details page (template-parts/content-single.php), search results page (template-parts/content-search.php), etc.
<?php echo getPostViews(get_the_ID());?>
The following is my personal blog. Add the code to display the reading volume and the actual display effect.