First thing we need to do is create a function that will detect post views count and store it as a custom field for each post. To do this, paste the following codes in your theme’s functions.php file or better in a site-specific plugin:
Tables can't be imported directly. Please insert an image of your table which can be found here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Now that you have this function in place, we need to call this function on the single post pages. This way the function knows exactly which post gets the credit for the views. To do this, you would need to paste the following code inside your single post loop:
Tables can't be imported directly. Please insert an image of your table which can be found here.
1
If you are using a child theme or you just want to make things easy for yourself, then you should simply add the tracker in your header by using wp_head hook. So paste the following code in your theme’s functions.php file or the site-specific plugin:
Tables can't be imported directly. Please insert an image of your table which can be found here.
1 2 3 4 5 6 7 8 9
Once you have placed this, every time a user visits the post, the custom field will be updated.
Note: If you are using a caching plugin, this technique will NOT work by default. We are using W3 Total Cache, and it has the feature called Fragmented Caching. You can use that to make this work just fine. Here is what needs to be changed:
Tables can't be imported directly. Please insert an image of your table which can be found here.
1
Now, you can do all sort of cool stuff such as display post view count, or sort posts by view count. Lets take a look at how to do some of these cool things.
If you want to display the post view count on your single post pages (often next to the comment count or something). Then the first thing you need to do is add the following in your theme’s functions.php file or the site-specific plugin.
Tables can't be imported directly. Please insert an image of your table which can be found here.
1 2 3 4 5 6 7 8 9 10
Then inside your post loop add the following code:
Tables can't be imported directly. Please insert an image of your table which can be found here.
1
If you want to sort the posts by view count, then you can do so easily by using the the wp_query post_meta parameter. The most basic example loop query would look like this:
Tables can't be imported directly. Please insert an image of your table which can be found here.
1 2 3 4 5 6 7 8
To add other WP_Query parameters such as time range, refer to the WP_Query page on Codex.