Home  >  Article  >  CMS Tutorial  >  Detailed explanation of how WordPress article readings are counted and displayed (not a plug-in)

Detailed explanation of how WordPress article readings are counted and displayed (not a plug-in)

藏色散人
藏色散人forward
2021-06-21 16:16:313771browse

The following tutorial column of WordPress will introduce to you WordPress article reading statistics and display (not a plug-in, refreshing the page will not add up). I hope it will be helpful to friends who need it!

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[&#39;views&#39;.$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.

Detailed explanation of how WordPress article readings are counted and displayed (not a plug-in)


The above is the detailed content of Detailed explanation of how WordPress article readings are counted and displayed (not a plug-in). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete