In this tutorial, we're going to create a basic popular post section that can be embedded anywhere on a WordPress website via short code. This utility will rank posts based on the number of page views that they have received over their lifetime. It's a simple implementation that should serve as an example of how you can create a popular post section in WordPress without the need of an additional plugin, or complex integration into Google analytics.
With that said, this implementation should only be used on hobby and low traffic websites. There are great plugins out there that you can use for popular posts, that are much more robust than this collection of code.
To achieve our desired outcome, there are three core components of our popular posts set up. First, we need a way to store the number of page views each post gets. Then, we need to add to the number of page views every time a post is viewed. Finally, we need to query posts based on the number of page views from highest to lowest, and output it in HTML via short code.
Create a "view" when somebody reads the post
This function will save a post for you to meta field that we will generate in step 2, every time it is called for a specific post ID.
Register Meta Field
This function and associated action adds a metafield to the WordPress post type called post_views. This is where the first function will add a page view to.
Query and create "most popular posts" shortcode
This code generates a short code, querying the most popular WordPress post by sorting based on the metal field post views. It will show the top 10 posts ranked from the highest number of pages to the lowest number of page views, based on the value in the meta-field. And then generates an HTML list, which can be output anywhere on the site.
Show viewcount in admin table
A helpful addition that will show the view count in the admin table for posts:
And just like that, we have created a basic way to display the most popular post based on page views on WordPress without a plugin. Of course, this is a really simple and quick implementation of this type of system, and if you were going to use it on a high traffic production website, there are many better ways to do it. However, this is a great primer on basic WordPress skills, like creating functions, using meta field, querying and using shortcodes.