Home > CMS Tutorial > WordPress > body text

What code does WordPress need to use to query page views?

Release: 2019-07-17 09:38:34
Original
2599 people have browsed it

What code does WordPress need to use to query page views?

Blogs or corporate websites built with wordpress have the same needs, that is, the number of views of this page needs to be counted on the content page to facilitate the webmaster to check the imitation problems of a certain page. Generally, friends who are not familiar with the code will use the view count plug-in (WP-PostViews), but as we all know, if too many plug-ins are installed on a site, it will be very detrimental to SEO optimization, so let me share with you a code to achieve this. Statistics function of the number of views.

1. Start a new line at the end of the functions.php function file and add the following code.

<?php
/* Postviews start */
function getPostViews($postID){
    $count_key = &#39;post_views_count&#39;;
    $count = get_post_meta($postID, $count_key, true);
    if($count==&#39;&#39;){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, &#39;0&#39;);
        return " 0 ";
    }
    return $count;
}
function setPostViews($postID) {
    $count_key = &#39;post_views_count&#39;;
    $count = get_post_meta($postID, $count_key, true);
    if($count==&#39;&#39;){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, &#39;0&#39;);
    }else{
       $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
/* Postviews start end*/
?>
Copy after login

2. On the page where you need to display the number of statistical views, such as and

<?php setPostViews(get_the_ID());?>
Copy after login

The display after adding, such as:

 
     <?php setPostViews(get_the_ID());?>
Copy after login

3. Finally, add the following code where you need to display statistics:

<?php echo getPostViews(get_the_ID()); ?> 次浏览
Copy after login

For more wordpress related technical articles, please visit the wordpress tutorial column to learn!

The above is the detailed content of What code does WordPress need to use to query page views?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template