All code samples have been moved to a GitHub Gist.
Tracking popular posts in WordPress often involves the use of a plugin. Many of the popular posts plugins out there come with tons of configurable options that you don’t need.
If you’re interested in a simple, bare bones method for tracking the popularity of a page, post or post type then perhaps this handy function will help you out.
Track Popular Posts
This is_singular()
and is_user_logged_in()
functions allow us to only run the process on individual posts, pages or post types when the visitor is not logged into WordPress.
PHP sessions track only one view per visitor per post. If all the conditions are met the post count is stored in a hidden custom field: _base_popular_posts_count
. If the field doesn’t exist we start with 1, if it does we add 1 onto the existing value.
To verify that the view count is being tracked you can add show_count=1
to your URL on any individual post to view details about the number of views for a post.
Display Popular Posts
Once we have the view count stored we can display popular posts in our theme using a custom WP_Query loop.
The meta_key
argument will find all posts that have the _base_popular_posts_count
custom field set. We can show the posts in order of popularity by setting the orderby
parameter to meta_value_num
.
Displaying Popular Posts for a Specific Time Range
For higher volume websites we can display popular posts for a specific time range using some of the WP_Query date and time parameters.
Today’s Popular Posts
By using the results of the PHP getdate()
function as year
, monthnum
and day
parameters in our WP_Query we can show posts from the current day.
Popular Posts This Week
Similar to the example above, we can display the most popular posts this week using the PHP date()
function with the w
parameter.
Popular Posts This Month
Similar to the example above, we can display the most popular posts this month using the PHP date()
function with the monthnum
parameter.
Hopefully you have a better understanding of how to track and display popular posts in WordPress without a plugin. As always, let me know if you have any questions!