How to Track Popular Posts by Views in WordPress Without a Plugin (2023)
Do you want to leverage your most popular content to drive more traffic and engagement on your WordPress site? Displaying a list of your top posts by view count is a proven tactic for keeping visitors on your site longer. This can lead to benefits like a lower bounce rate, more time on site, and ultimately higher conversions.
The easiest way to track and display popular posts by views is using a WordPress plugin. But plugins can bloat your site and hurt performance, especially if you‘re using multiple plugins already. Luckily, with a few lines of code, you can track post views and show popular posts – no plugin required.
In this guide, you‘ll learn exactly how to track your most popular WordPress posts by views without using a plugin. We‘ll walk through the steps to implement post view tracking, display a popular posts widget, and style it to match your theme.
We‘ll also compare this method to using a plugin and share some tips to get the most value from your popular posts data. Let‘s dive in!
Why Track Your Most Popular Posts by Views?
Before we get into the technical details, it‘s worth understanding the benefits of displaying your most popular content by views:
- Improve navigation and content discovery. Highlighting top posts helps visitors find your best content quickly.
- Boost engagement metrics. Encouraging visitors to view more pages leads to a lower bounce rate and more time on site. These engagement signals can indirectly help SEO.
- Increase conversions. Keeping users on your site longer gives you more opportunities to convert them into subscribers or customers.
- Inform your content strategy. Knowing which posts perform best helps you produce more content that resonates with your audience.
- Impress prospective sponsors and partners. High view counts on your top posts demonstrate the value of your site.
While you can get some of these benefits by showing a generic list of recent posts, tracking views allows you to showcase your top content by popularity. This personalizes the experience based on your audience‘s behavior.
You can even take it a step further and display top posts segmented by category or tag. This keeps the recommendations as relevant as possible to the current post‘s topic.
Now that you know the "why" behind popular post tracking, let‘s look at how to implement this on your WordPress site.
How to Track Post Views in WordPress Using Code
The standard way to track and display popular posts is with a WordPress plugin like MonsterInsights or WordPress Popular Posts. These plugins automatically track views and generate a popular posts widget you can add anywhere on your site.
However, using a plugin may not be the best route if:
- You‘re concerned about plugin bloat slowing down your site
- You want full control and customization over how views are tracked and displayed
- You don‘t need some of the more advanced features in popular post plugins
With a few code snippets, you can add view tracking and a basic popular posts widget to your theme. Here are the steps:
- Add a post views counter function
First, we need to create a function that registers a view each time a post is visited. Add this code to your theme‘s functions.php file or in a site-specific plugin:
function wpb_set_post_views($postID) {
$count_key = ‘wpb_post_views_count‘;
$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);
}
}
//To keep the count accurate, let‘s get rid of prefetching
remove_action( ‘wp_head‘, ‘adjacent_posts_rel_link_wp_head‘, 10, 0);This code does a few things:
- Checks if the current post already has a view count stored in the post meta. If not, it initializes the count to zero.
- Increments the view count by one and updates the post meta.
- Removes the adjacent_posts_rel_link from the wp_head action hook to prevent prefetching from artificially inflating view counts.
- Call the post views counter function
Next, we need to call our wpb_set_post_views function when a post is viewed. Add this snippet to functions.php:
function wpb_track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
wpb_set_post_views($post_id);
}
add_action( ‘wp_head‘, ‘wpb_track_post_views‘);Here‘s what this code does:
- Checks if we‘re on a single post page. If not, it stops the function.
- Checks if the $post_id variable is empty. If so, it gets the current post ID.
- Calls the wpb_set_post_views function for the current post, which increments the view count.
Note: If you use a caching plugin, you may need to configure fragment caching to ensure view counts are tracked accurately. Check your caching plugin‘s documentation for guidance.
- Create a function to retrieve the post view count
To display the view count for each post, we need a helper function that retrieves the number of views from the post meta. Add this to functions.php:
function wpb_get_post_views($postID){
$count_key = ‘wpb_post_views_count‘;
$count = get_post_meta($postID, $count_key, true);
if($count==‘‘){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, ‘0‘);
return "0 views";
}
return $count.‘ views‘;
}This snippet checks if the current post has a view count stored. If not, it sets the count to zero and returns "0 views". If there is a count value, it returns it with " views" appended to the end.
We‘ll use this function in the final step to display the view count next to each post in the popular posts widget.
- Display the most popular posts
The final step is to create a function that queries the database for posts with the highest view counts and displays them in a list or grid.
You can add this code directly to your single.php template file, or in functions.php wrapped in a conditional tag to display only on single post pages.
Here‘s a sample popular posts function:
function display_popular_posts() {
// Query the database for the 5 posts with the highest view counts
$popular_posts_query = new WP_Query(
array(
‘posts_per_page‘ => 5,
‘meta_key‘ => ‘wpb_post_views_count‘,
‘orderby‘ => ‘meta_value_num‘,
‘order‘ => ‘DESC‘
)
);
// Check if any posts were returned
if ( $popular_posts_query->have_posts() ) {
echo ‘<div class="popular-posts-wrapper"><h3>Popular Posts</h3><ul>‘;
while ( $popular_posts_query->have_posts() ) {
$popular_posts_query->the_post();
// Display each post title and view count
echo ‘<li><a href="‘ . get_the_permalink() . ‘">‘ . get_the_title() . ‘</a> - ‘ . wpb_get_post_views(get_the_ID()) . ‘</li>‘;
}
echo ‘</ul></div>‘;
}
// Reset the post data
wp_reset_postdata();
}This code does the following:
- Queries the database for the 5 posts with the highest view counts using a custom WP_Query.
- Loops through the returned posts and outputs the title and view count for each one.
- Wraps the list in a div with a class of "popular-posts-wrapper" for easy styling.
- Resets the post data to the main query when finished.
Feel free to customize the HTML markup and query parameters to fit your needs. You may also want to add some CSS to style the popular posts widget to match your theme.
Some customization ideas:
- Change the number of posts displayed by modifying the posts_per_page parameter.
- Filter the popular posts by category or tag by adding a tax_query parameter to the WP_Query arguments.
- Exclude certain post types or posts by ID using the post_type and post__not_in parameters.
- Output the post thumbnail along with the title by adding get_the_post_thumbnail() inside the while loop.
- Use a grid layout instead of a list by changing the markup and CSS.
Comparing This Method to Using a Plugin
Now that you‘ve seen how to implement post view tracking manually, let‘s compare this method to using a popular post plugin.
Advantages of using code snippets:
- No extra plugin to install and maintain
- More control over exactly what data is tracked and displayed
- Leaner code and smaller performance impact
Advantages of using a plugin:
- Easier, codeless setup and customization
- More design options for the popular posts widget
- Advanced features like tracking views per author or adding thumbnails
Neither method is inherently better than the other. If you‘re comfortable editing code and want simplicity, tracking views manually may be the way to go. If you want an out-of-the-box solution and don‘t mind adding another plugin, you might prefer that route.
You can even combine both methods for more granular control while still leveraging a plugin‘s enhanced widget design and backend reporting.
Tips for Getting More From Your Popular Posts
However you implement view tracking, there are some additional ways to capitalize on your popular content:
Promote top posts to email subscribers and social media followers. Create a weekly or monthly "top posts" roundup and share previews of your best content to drive more traffic.
Use popular posts data to inform your editorial planning. Note which topics and formats get the most views and produce more content along those lines. You can even update and republish high-performing posts to get more mileage from them.
Conduct A/B tests on your popular posts widget design. Test different locations, thumbnail sizes, fonts, and more to increase the click-through rate on your popular posts. Just be sure to let each test run long enough to reach statistical significance before drawing conclusions.
Add an inline call-to-action (CTA) to your most popular posts. Take advantage of the extra visibility to promote an offer, grow your email list, or highlight a product.
Monitor other engagement metrics on your popular posts. Views alone don‘t tell the full story. Keep an eye on metrics like time on page, bounce rate, and scroll depth in Google Analytics to better understand how users are interacting with your top content.
FAQs About Tracking Popular Posts in WordPress
To conclude, let‘s answer some common questions about tracking popular posts in WordPress.
Can I track post views without affecting performance?
Yes, you can! Tracking post views doesn‘t require a ton of extra code or database queries. As long as you‘re not going overboard with plugins or tracking scripts, the performance impact should be minimal.
How can I exclude certain posts or pages from the popular posts list?
To exclude specific posts or pages, you can add their IDs to the post__not_in parameter in the WP_Query arguments. For example:
‘post__not_in‘ => array( 123, 456, 789 )This would exclude posts with the IDs 123, 456, and 789 from the popular posts widget.
You can also exclude entire post types by modifying the post_type parameter:
‘post_type‘ => ‘post‘ This would only include posts, not pages or custom post types, in the popular posts list.
What‘s the best way to style the popular posts widget?
The specifics will depend on your theme, but in general, you‘ll want to:
- Match the font family, size, and color to your theme‘s typography
- Add sufficient padding and margins around the widget and between list items
- Style links to be consistent with the rest of your site
- Optionally, add thumbnail images to make the widget more visual
- Make sure the widget looks good on both desktop and mobile devices
You can add custom CSS to your theme‘s stylesheet or use the Additional CSS field in the WordPress Customizer.
Are post views a reliable measure of popularity?
Post views can be a good proxy for popularity, but they‘re not perfect. Factors like search engine ranking, social media shares, and email clicks can all influence view counts.
Additionally, not all views are created equal. A post with a high number of views but a high bounce rate may not be truly "popular" in the sense of engaging readers.
It‘s best to look at post views in conjunction with other engagement metrics to get a fuller picture. You can also combine view data with other popularity signals like comments and social shares to rank your top content.
I use a caching plugin. Will post views still be tracked?
By default, caching plugins can interfere with post view tracking by serving a cached version of the page instead of processing the view counter script.
To get around this, you can use a technique called fragment caching to exclude the popular posts section from being cached. Most caching plugins support fragment caching, but the setup steps vary.
Generally, you‘ll need to wrap the popular posts code in a pair of caching tags to tell the plugin not to cache that section. Check your caching plugin‘s documentation for specific instructions.
Wrapping Up
Tracking popular posts by views is a smart way to keep visitors engaged with your best content and drive meaningful results for your site.
While using a plugin is the simplest way to enable post view tracking in WordPress, you can also do it with just a few code snippets. This gives you more control while keeping your site lean and fast.
Follow the steps in this post to implement post view tracking on your WordPress site. Then leverage your popular posts data in your content planning, audience development, and conversion optimization efforts.
By putting your best foot forward with popular content, you‘ll delight readers and keep them coming back for more!
