Tutorial: Get post views to work when using W3TC cache
After days of trial and error on how to get post views to work (increase) when viewing a post when using caching plugin W3TC, we finally found a super simple method that actually works!
In our case we wanted to keep everything super nice and tidy so we created our own simple plugin to insert the function we need into.
In the code below and in all the steps below, replace ‘websitename’ with the name of your own website.
1: To make the simple plugin, just create an empty text file, then insert this code into it:
[php] < ?php /* Plugin Name: Site Plugin for websitename Description: Site specific code changes for websitename */ /* Start Adding Functions Below this Line */// post views function setAndViewPostViews($postID) { $count_key = 'views'; $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); } return $count; /* so you can show it */ } /* Stop Adding Functions Below this Line */ ?>[/php]
2. Save the file as for example websitename-plugin.php
3. Then create a new folder named websitename-plugin, in your plugins directory (usually this is in wp-content/plugins ). Upload the .php file into the folder you created.
4. Activate the new plugin in WordPress plugins page.
5. Add the following line of code in the theme file single.php:
[php] < ?php setAndViewPostViews(get_the_ID()); ?>[/php]
This method has been tested to work on a single site.
We hope that this will save you days / hours of time to find a way to get the views to work.
The sources of information on how to get this working we got from using information from multiple sites, the site that explained how to make a site-specific WordPress Plugin we got from wpbeginner and the function to get page views we got from wordpress stackexchange.com.
It’s likely that you can just add the function in functions.php instead of creating a plugin, but we have not tried that as we wanted to keep it nice and tidy and so we can enable and disable our plugin easily.
Need a web video? For work examples of our unique, custom, fun and original animated explainer videos, ‘how does it work’ videos, infographics videos, corporate videos and motion graphics go here.