How many views count of your blog posts or topics? Sorry, but wordpress does not support us this function. You can search plugins for “post view count” and add one. But now, I will show you another way to display the posts’ views count, by using php code without any plugin. Follow me!
Dear wordpress support us four lovely functions, add_post_meta, get_post_meta, update_post_meta, delete_post_meta, every function’s reference is shown with it’s link, you can just click it. As you can read them, the things the function will do you can get it! Yes, add, get, update, and delete, you can define any meta of post. So, we can define a key named “
As you can see,
What is next? Where shall we put the code? Follow the below steps:
Save the code as a php file named
Open your
And open
The result is, when a visitor hit the post’s title and open it, the views count will increase by 1, and the number is displayed at where you put it.
Dear wordpress support us four lovely functions, add_post_meta, get_post_meta, update_post_meta, delete_post_meta, every function’s reference is shown with it’s link, you can just click it. As you can read them, the things the function will do you can get it! Yes, add, get, update, and delete, you can define any meta of post. So, we can define a key named “
post_views_count
“. Now look at the core code below:<?php function getPostViews($postID){ $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } return $count.' Views'; } function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } ?>
getPostViews($postID)
will return a number that represent a post views count which post id equals $postID
, and setPostViews($postID)
will make the post views count increase by 1.What is next? Where shall we put the code? Follow the below steps:
Save the code as a php file named
post-views.php
and put it in your theme path, the same path of the theme main file index.php
. Open your
index.php
of wordpress theme, add require("post-views.php");
before while(have_posts())
, and put <?php echo getPostViews(get_the_ID()); ?>
in where you wana display the views count, but must between the while
and endwhile
. And open
single.php
, add require("post-views.php");
before while(have_posts())
too, put setPostViews(get_the_ID())
; after while (have_posts()) {
, then we done. The result is, when a visitor hit the post’s title and open it, the views count will increase by 1, and the number is displayed at where you put it.
No comments:
Post a Comment