Jun 16, 2019, 03:48 pm

News:

All student forum is just for you, what questions do you have?


How to Show The Number of Views of a Post on WordPress

Started by 4niso, May 29, 2019, 10:56 pm

Previous topic - Next topic

4niso

Have you been looking for a way to show the number of post view on your post page? you may wish to display the total number of view of your post on wordpress, probably the template you are developing with has no such ability. Well here are few steps to get this done.
The first thing you will want to do is to pick up the WP PostViews plugin.
While there are a number of post view plugins out there, this one has an option to discount the views of bots to a page - something pretty important, obviously, but also something a number of these plugins don't do.
In order to show the view count on a post, you merely need to put the following code into your single.php template:
{code type=php}
<?php if(function_exists('the_views')) { the_views(); } ?>
{/code}

That's easy enough, but now we'll go over controlling who can see that view count.
Choosing Who Sees the View Count
Another nice aspect of this plugin is that it actually comes with some built-in control to determine who sees the view count (and on what type of page too - post, homepage, etc.).
You can choose to show the view count to everyone, to only logged in users, or to only logged out users.

This is a nice function, but it's a little limited. And so we're going to hack that a little and make it even more flexible.
One a site with a number of different writers, it seems only logical that you might want to let the writers see the number of views on posts they have written. For whatever reason, you might not want others to see that, people such as the general public, other writers, or visitors who have some kind of low level permission like "Subscriber" on the site.
And so here's the code that will let you do that:
{code type=php}
<?
if ( current_user_can( 'edit_post' , get_the_ID() ) && function_exists( "the_views" ) ) {
the_views();
}
?>
{/code}
By checking the "edit_post" capability and passing the post_id, we restrict the view count to the author of the post, the Editor and the Admin.
Whether limiting the viewers or not, here's what the basic output will look like.

Other Functions in the Plugin
while the main purpose of this post is getting the view count of an individual post onto the post page itself, there are a number of other functions the plugin offers (another reason for choosing this one).

In addition to coming with a widget, you can insert code into your template files to create a number of automatically generated lists, such as ...
•   most viewed posts
•   least viewed posts
•   most views posts by tag
•   least views posts by tag
•   most views posts by category
•   least views posts by category
See the plugin's homepage for more info on all this.
photos credit: Navy binoculars

Source: Premium


4niso