Home  >  Article  >  CMS Tutorial  >  What code does WordPress need to use to query page views?

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

尚
Original
2019-07-17 09:38:342598browse

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*/
?>

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

<?php setPostViews(get_the_ID());?>

The display after adding, such as:

 
     <?php setPostViews(get_the_ID());?>

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

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

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!

Statement:
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