How to Display Popular Posts by Day, Week, and Month in WordPress

Do you want to display your most popular posts by day, week, month, or even all-time in WordPress?

Popular posts allow your visitors to quickly discover your top content, which helps you increase user engagement, pageviews, and conversions.

In this article, we will show you how to display popular posts by day, week, month, and all time in WordPress.

Display popular posts by day week month and all time in WordPress

Why Display Popular Posts in WordPress?

When you start a WordPress blog, you don’t have much content, which allows you to display selected posts in a sidebar widget manually.

However, as your website grows, you will notice that older articles on your website don’t get much exposure. By showcasing your top content, you allow new users to quickly discover the best articles on your website. This boosts user engagement on your website and increases your page views.

Now the problem is that if you are showing your all-time popular articles, then a very limited set of articles get repeated exposure. You can diversify it by displaying popular posts by day, week, or month as well.

Let’s take a look at how to easily display popular posts in WordPress by day, week, month, or all time.

Add Popular Posts by Day, Week, and Month in WordPress

The best way to show popular posts in WordPress is using MonsterInsights. It’s the best Analytics plugin for WordPress and helps you set up Google Analytics without editing code.

For this tutorial, we’ll use the MonsterInsights Pro version because it lets you automatically show top posts from Google Analytics.

There is also a MonsterInsights Lite version that’s free and also includes the Popular Posts feature, but does not connect to GA.

First, you’ll need to install and activate the MonsterInsights plugin. If you need help, then please see our guide on how to install a WordPress plugin.

Upon activation, you will be directed toward the MonsterInsights welcome screen. Go ahead and click the ‘Launch the Wizard’ button.

Launch setup wizard

After that, you can follow the onscreen instructions to configure Google Analytics. For more details, please see our guide on how to install Google Analytics in WordPress.

With MonsterInsights, you can also set up a Google Analytics 4 property. This is the new version of Analytics. The previous Universal Analytics version will sunset on July 1, 2023, and you won’t be able to track website data after this date. That’s why now is the best time to switch to Google Analytics 4 and protect your data.

Now that you’ve added Google Analytics to your website, the next step is to go to Insights » Popular Posts from your WordPress dashboard.

MonsterInsights lets you show your top articles within the content, in the sidebar as a widget, and display popular products if you have an online store.

For this tutorial, we’ll use ‘Inline Popular Posts’ and show featured articles within the content of other blog posts.

Popular post in MonsterInsights

The plugin comes with prebuilt themes, and you can see a preview of how your popular posts will appear on the website.

Once you’ve chosen a theme, simply scroll down to see more customization options. For instance, you can change the title color and size, edit the color of the label and background, and more.

Preview of popular post and customization options

Show Popular Posts by Day, Week, Month, and All Time in WordPress

Next, you’ll need to choose how the plugin will determine your popular posts. Let’s see how you can show posts by day, week, month, and all time.

Displaying Popular Posts by Day, Week, and All Time

In MonsterInsights, you can manually select which posts appear in the Popular Posts widget.

This is useful when displaying top content from a specific day or week. Plus, you can also show your all-time best articles anywhere on your website.

Simply select the ‘Curated’ option under Sort By section and then choose the articles you want to feature.

These could be your evergreen content, weekly announcement or news, trending topics from a particular day, and more.

Just begin typing the name of the posts you want to include, and then select them as their name pops up in the field. To continuously display your top posts of all time, you simply need to select them, and as long as ‘Curated’ is chosen, they will appear as popular posts.

Select curated articles to feature

However, if you want to display popular posts by the day or the week, you will have to manually change some of these curated posts so they stay fresh for your audience.

For instance, if you are featuring different WooCommerce products weekly, you will need to choose which posts are listed under ‘Curated’ each week.

Displaying Popular Posts by Month and All Time

In MonsterInsights, you get multiple options to automatically show popular posts by month and all time.

First, you can show your most commented pages from the last 30 days by selecting the ‘Comments’ option. The plugin will randomly rotate blog posts with the highest comments and show them in the popular post widget.

Sort your popular posts

Similarly, MonsterInsights also lets you automatically display popular posts based on social shares using the ‘SharedCount’ option.

It integrates with the SharedCount and helps you display your all-time most shared articles. This way, people can easily find content that’s driving social engagement.

Show popular posts by SharedCount

MonsterInsights also offers an option to show the top 5 posts from Google Analytics in the last 30 days. This way you can show your top-performing content from last month or all-time anywhere on your site.

First, you’ll need to select the ‘Curated’ option under the ‘Sort By’ section.

After that, you can enable the ‘Add Top 5 Posts from Google Analytics’ option under the Automated + Curated section.

Add top 5 posts automatically

To ensure that your data is being fetched from Google Analytics, click the ‘Test Automated Posts’ button under ‘Automated + Curated.’

A popup message will now appear, showing that the popular posts are being fetched correctly. You can click the ‘Close’ button.

Popular post data is correctly fetched

Do note that you’ll need to set up the ‘Post Type’ custom dimensions in MonsterInsights and Google Analytics to use the Automated + Curated feature.

Custom dimensions are additional metrics you can track in Google Analytics. For more details on custom dimensions and how to configure them, you can see our guides on how to enable author tracking in WordPress and the best time to publish a blog.

Insert Popular Posts to Your WordPress Website

Next, you’ll need to select how you’d like to insert the featured articles.

MonsterInsights offers 2 options, including automatic placement and manual placement.

If you select the ‘Automatic’ option, then you can decide after how many words you’d want the popular post widget to appear. There is also an option to include and exclude pages from display featured posts.

Choose placement option

When you’re done, simply click back to the top and click the ‘Save Changes’ button.

This way, your settings will be saved, and MonsterInsights will automatically display popular posts on your site.

Click the Save Changes Button to Store Your New Widget

On the other hand, you can also show popular posts in any blog post by adding the MonsterInsights block or using a shortcode.

First, add a new post or edit an existing one. Once you’re in the content editor, simply click the ‘+’ button and add the ‘Popular Posts’ block.

Select popular posts block

After that, you can see a preview of your featured articles in the content editor.

Once you’re satisfied with the widget’s appearance, you can go ahead and publish your article.

Preview your popular posts

We hope this article helped you display popular posts by day, week, month, and all time in WordPress. You may also want to see our guide on WordPress SEO and the best WooCommerce plugins.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Display Popular Posts by Day, Week, and Month in WordPress first appeared on WPBeginner.

How to Add a Stats Dashboard On Your WordPress Site

Do you want to add a stats dashboard on your WordPress site?

Analytics helps you discover how people find and use your website, so you can keep them coming back.

In this article, we will show you how to easily add a stats dashboard on your WordPress site.

How to add a stats dashboard on your WordPress site

Why You Need a Stats Dashboard in WordPress

Usually, you can install Google Analytics and view your reports by logging into your Google account. This sounds great, but many people forget to check their blog stats on a regular basis.

The two biggest reasons for that are:

  1. You have to log in to a separate website like Google Analytics to check the stats.
  2. You have to dig around in the Google Analytics dashboard to find what you’re looking for.

While GA is a powerful tool, it often takes a lot of time and clicking around to get to the data you want to view. Most beginners never make it this far.

Adding a stats dashboard to your WordPress website solves this problem. You will be able to quickly view the stats that matter without leaving your WordPress admin area.

That said, let’s take a look at how to easily add a stats dashboard on your WordPress site.

Adding a Stats Dashboard in WordPress

The best way to add a stats dashboard in WordPress is by using MonsterInsights. It’s the best Analytics solution for WordPress, and it helps you set up Google Analytics in WordPress without editing code.

For this tutorial, we will use the MonsterInsights Pro version because it includes powerful addons and advanced tracking features such as affiliate link tracking, eCommerce tracking, and dashboard reports.

There is also a MonsterInsights Lite version you use for free. It helps you configure Google Analytics in WordPress and shows a quick overview report in the dashboard.

The first thing you need to do is install and activate the MonsterInsights plugin. For more details, see our step-by-step guide on how to install a WordPress plugin.

Upon activation, you’ll be taken to the MonsterInsights welcome screen. Simply click the ‘Launch the Wizard’ button and follow the onscreen instructions to set up Google Analytics.

Launch setup wizard

For more details, please see our guide on how to install Google Analytics in WordPress.

Now, let’s look at the stats dashboard MonsterInsights adds on your site.

How to Add Stats to WordPress Dashboard

On your main WordPress dashboard screen, MonsterInsights adds a widget that shows stats about your site’s performance. You can quickly view your website traffic and identify top posts and pages.

Simply log in to your WordPress admin panel. On the home screen, you’ll see the MonsterInsights dashboard widget.

Dashboard widget stats

You can also click the expand icon at the top and view the dashboard widget report in full-width mode to get more details.

The expanded widget displays the number of sessions, pageviews, average session duration, and bounce rate in the last 30 days.

Additionally, it also shows your top-performing posts and pages, new vs. returning visitors, and a device breakdown.

Expand dashboard widget report

Next, let’s see how MonsterInsights helps you view statistics for each blog post and landing page in the WordPress dashboard.

See Page and Post Stats in WordPress Dashboard

To see how individual articles and pages perform, you can use the MonsterInsights Page Insights addon.

First, you can head to Insights » Addons from the WordPress admin panel and navigate to the ‘Page Insights’ box. Go ahead and click the ‘Install’ button.

Install page insights addon

The addon will now automatically install and activate on your site.

Next, you can go to Posts » All Posts from your admin panel to see the stats of individual posts.

You’ll see an ‘Insights’ column added to your WordPress posts and pages screen.

View insights column in dashboard

A small window will open if you click the ‘Insights’ icon for any blog post.

You can then view stats for a specific post or page. For instance, the plugin shows stats for only that post, including bounce rate, entrances, page views, time on page, page load time, and exits.

MonsterInsights page insights reports

Using these stats, you can find out how your content is performing without having to leave your WordPress dashboard.

On top of that, MonsterInsights also lets you see stats for any post or page from the front end of your site. When viewing any post or page, you can simply click the ‘Insights’ button in the admin bar to see 30 days of performance stats for that post.

View insights stats on frontend

Viewing More WordPress Stats with MonsterInsights

With MonsterInsights, you get easy-to-understand dashboard reports. It neatly organizes data from Google Analytics and helps you make data-driven decisions.

Here’s a quick rundown of the reports you can see in MonsterInsights and how you can use them.

Overview Report

To view your WordPress stats dashboard, simply go to the Insights » Reports page.

First, you’ll see the ‘Overview Report.’ At the top, you will see two tabs, each giving you a graph of your WordPress visitor sessions or pageviews. This gives you a quick overview of incoming traffic to your website.

Overview report in MonsterInsights

Below that, you will see a comparison of your website stats against the previous 30 days. These boxes will show the number of sessions, page views counter, session duration, and bounce rate.

Below that, you will see a chart showing new vs. returning visitors. You can use these stats to see how many people return to your site. Similarly, there is a device breakdown chart, which helps you optimize your site for different devices.

Device breakdown and top countries report

This is followed by a list of the top countries people visit your website from, as well as the top websites that send the most traffic your way. You can use the top countries report to set up geolocation targeting, create personalized messages, and boost conversions.

MonsterInsights also acts as a pageview counter and shows your most popular WordPress posts and pages. This helps you find your top-performing content so that you can plan your content strategy accordingly.

Top posts and page report

Publishers Report

In the Publishers report, you get more details about the performance of your content. It’s great for content-rich websites like blogs, news, or magazine sites.

The report shows your top landing pages and the number of visits, average duration, and bounce rate they got in the last 30 days.

Top landing pages report

You can also view the top exit pages and see from where people leave your website. It helps optimize any WordPress blog a high exit rate. For example, you can show a popup and offer a free ebook to leaving visitors in exchange for their email addresses.

If you scroll down, then you’ll see reports on top outbound links and top affiliate links. With the help of these 2 reports, you get to track link clicks on your site.

Outbound and affiliate links report

For example, you can see which affiliate is performing the best, so you can promote it more on your site. Similarly, outbound link tracking helps create new partnership opportunities where you can get more backlinks, sign up for an affiliate program, and more.

MonsterInsights also helps track file downloads on your site. It shows which download links are getting the most clicks. This way, you can uncover the type of downloadable content your audience prefers.

Lastly, you get to see your visitor’s demographics and interests in the Publishers report. MonsterInsights will show the age and gender of your audience and their interests.

Demographics and interest reports

The plugin also enables scroll tracking on your site. It shows how far people scroll your content before exiting. You can use this information to improve conversions and placement of call-to-action (CTA) buttons and ads.

Search Console

If you’ve connected Google Search Console with Google Analytics, then MonsterInsights will show the top 50 search terms in your WordPress dashboard.

Simply visit the search console report and find out which keywords people use to find your website on the internet. You also get to see the number of clicks, impressions, CTR, and average position for each search term.

Search console report

Using the report, you can optimize keywords close to reaching the top 10 positions in Google search and increase your organic traffic. Plus, the report helps perform keyword research and uncover new search term ideas for your site.

eCommerce Report

If you run an online store or a membership website, then you’ll love MonsterInsights eCommerce tracking features.

MonsterInsights offers an eCommerce addon that helps track your online store’s performance in Google Analytics. The best part is that MonsterInsights works with popular eCommerce plugins like WooCommerce, MemberPress, Easy Digital Downloads, GiveWP, and more.

For more details, please see our guide on how to set up eCommerce tracking in WordPress.

To view stats about your online store, you can head to the eCommerce tab.

eCommerce reports

In the reports, you will see a breakdown of conversion rate, transactions, revenue, and average order value. This gives you a quick overview of your store’s performance.

Besides that, MonsterInsights also shows top products on your website. For instance, if you have a WooCommere store, then you can see which product your customers like to buy the most. This way, you could find similar products or bundle different items together to boost sales.

MonsterInsights also shows your top conversion sources. These are sites that send the most sales to your store. You can partner with these sources and offer exclusive discounts to visitors from these websites.

Top conversion sources

Dimensions Report

With MonsterInsights, you can easily track additional information in Google Analytics that’s not possible by default and view them in the dimensions report.

For example, you can set up author tracking and see which writer’s posts attract the most visitors. Similarly, you can also track categories and tags using custom dimensions.

It also helps test the best publication time for your blog posts. This way, you can publish articles to get more engagement, comments, and shares.

Best publication time report

Forms Report

Do you want to see stats on how your online forms are performing?

MonsterInsights helps you track form conversions in Google Analytics and shows a report in your WordPress dashboard.

Simply view the Forms report and see which form gets the most impressions and conversions. This way, you can optimize low-performing forms and increase the visibility of forms that are converting well.

Forms report

Real-Time Report

A real-time report is great for getting up-to-the-minute stats about your website.

For example, a real-time report comes in handy if you’re running a flash sale and want to know how your campaign is performing. You get to monitor your website activities as they happen.

View real-time report in MonsterInsights

For more details, please see our guide on how to show real-time online users in WordPress.

Site Speed Report

The last report you’ll see in MonsterInsights is the Site Speed report. Although the report doesn’t relate to the website traffic, but it is crucial for your WordPress SEO and user experience.

Using the report, you can see an overall score of your site’s load time on mobile and desktop.

Site speed report

There are other metrics as well that you can use to improve your site’s user experience. MonsterInsights also provides recommendations for enhancing the score for these metrics and reducing the page load time.

You can see our guide on how to boost WordPress speed and performance for more tips and tricks.

We hope this article helped you learn how to easily add a stats dashboard in WordPress. You may also want to see our guide on how to start your own podcast or our expert pick of the best business phone services.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Add a Stats Dashboard On Your WordPress Site first appeared on WPBeginner.

How to Display Popular Posts by Views in WordPress (2 Ways)

Do you want to display popular posts based on their views in WordPress?

By showing your most popular WordPress blog posts, you can help readers find your best and most valuable content. Plus, it can encourage them to stay longer on your website.

In this article, we’ll show you how to display your popular posts by views in WordPress.

How to Display Popular Posts by Views in WordPress

Why Display Popular Posts by Views in WordPress?

When users see your most popular WordPress blog posts, they can discover what content their fellow readers like the most. This way, they can check those articles out and join in on the conversation.

What’s more, displaying your most popular content in WordPress can boost your social proof. It’s like telling new users that, “Hey, other people have found these posts really helpful, and you might too!”

WPBeginner's trending and popular posts

Finally, showing your trending blog posts can make people stay longer on your website and explore more of your content.

The more your user engagement increases, the more Google thinks your content is good and important. In turn, your site can rank higher. Plus, this gives readers more time to convert, like signing up for your newsletter.

Unfortunately, WordPress doesn’t have a built-in feature or block to display your most popular posts by page views. In this guide, we will show you how to do exactly that with a plugin and with code.

Just click on one of the quick links below to jump straight to your preferred method:

Video Tutorial

If you prefer written instructions, then just keep reading.

Method 1: Display Popular WordPress Posts by Views With MonsterInsights

The easiest way to display popular posts by views in WordPress is with a plugin. There are actually many WordPress popular post plugins available, but in our opinion, the best choice is MonsterInsights.

The MonsterInsights Google Analytics plugin

Used by 3 million+ websites worldwide, MonsterInsights is the best Google Analytics plugin for WordPress. While its main functionality is analytics, it also has a user-friendly feature to show your most popular posts.

First things first, you will need to install the MonsterInsights plugin and connect it to your Google Analytics account. For more details, see our step-by-step guide on how to install Google Analytics in WordPress for beginners.

Note: While a free version of MonsterInsights is available, we will be using the Pro version since it includes the popular posts feature.

Choose a Popular Posts Widget Theme

Once you’ve activated and set up the plugin, go to Insights » Popular Posts from the WordPress dashboard. Then, click the ‘Popular Posts Widget’ menu item.

The Popular Posts Widget in MonsterInsights

Scrolling down, you will need to select a theme to display the popular posts widget. There are various options.

Some include a featured image for the post, while some are more minimal-looking.

Choosing a popular posts widget theme in MonsterInsights

If you want to see what the theme looks like before making your choice, just move down the page to the Theme Preview section.

You can also preview the theme in a Wide or Narrow format. With the Wide format, you’ll see your posts listed under the page or post content, whereas the Narrow format displays the posts on the right side of it, like a sidebar.

Previewing the popular posts widget theme in MonsterInsights

Next, let’s scroll down to the ‘Customize Design’ section. Here, you can modify the theme’s colors, font size, layout, and post count to display.

The customization options here may vary depending on the theme you use. So, be sure to explore the different themes to see which one suits you best.

Customizing the popular posts widget theme in MonsterInsights

Configure the Popular Posts Widget Behavior

Once you’ve configured the theme’s design, you must go to the Behavior section. This is where you will control how the popular posts widget will appear on your WordPress website.

In the Widget Styling settings, you can choose to use the design that you’ve made above or opt to not style the widget at all. With the second option, the widget will follow your WordPress website theme’s CSS.

Then, you can choose how the widget should choose your most popular posts. Here, pick ‘Curated.’

Some of the popular posts widget's behavior settings in MonsterInsights

What you have to do next is enable the ‘Add Top 5 Posts from Google Analytics’ option below. But before doing that, you will need the MonsterInsights Dimensions Add-On and to add Post type as a new custom dimension.

This will let MonsterInsights choose the most popular posts based on Google Analytics data.

To do this, you have to download the MonsterInsights Dimensions Add-on and install it as a plugin in WordPress. For step-by-step instructions, check out our guide on how to install a WordPress plugin.

Next, go to Insights » Settings and switch to the ‘Conversions’ tab. After that, click ‘Add New Custom Dimension.’

Adding a new custom dimension in MonsterInsights

Once you’ve done that, select ‘Post type’ in the dropdown menu.

This will enable MonsterInsights to track the performance of your blog posts and other custom post types.

Selecting post type as a custom dimension in MonsterInsights

Now, just return to Insights » Popular Posts and go to ‘Popular Posts Widget.’

Simply activate the ‘Add Top 5 Posts from Google Analytics’ toggle button. Then, click ‘Test Automated Posts’ to see if the setup was successful.

Adding top 5 posts based on GA data in MonsterInsights

If yes, then you will see a success message popup.

It should say: ‘Popular Posts data can be fetched correctly. Please note: depending on when you set up the Custom Dimensions settings, it may take up to 7 days to see relevant Popular Posts data loading from Google Analytics.’

Popular posts data can be fetched correctly popup message in MonsterInsights

Moving on to the next steps, you can now add a title that will appear above the widget. It can be something like ‘Check Out Our Most Popular Posts’ or anything similar.

Below that, you can choose whether the widget should be displayed in all post types, be excluded from specific posts, and/or appear in certain post categories only.

These settings are useful if you have custom post types other than blog posts and feel like the popular posts widget will look irrelevant there.

More behavior settings for the popular posts widget in MonsterInsights

One of the last steps is to embed the popular posts widget. There are several options: placing it automatically, using a Gutenberg block, adding it as a sidebar widget, or using a shortcode.

Let’s go through each option one by one.

The embed options of popular posts widget in WordPress

Embed the Popular Posts Widget Automatically

Automatic Placement is recommended if you want the widget to show up on all the posts that match the Behavior settings you’ve set previously.

For this, all you have to do is activate the Automatic Placement button.

Activating automatic placement for the popular posts widget in MonsterInsights

The downside with this option is that you cannot adjust the widget’s design based on what looks best on the post or page. If you need this type of functionality, then you can try the next method.

Embed the Popular Posts Block to a Page or Post

If you want to have more control over how the widget looks on a page or post, then this method is for you.

First, go to the block editor of the post or page where you want the widget to be. After that, click the ‘+’ add block button anywhere in the editor and look for the Popular Posts block.

Adding MonsterInsights' popular posts block in the WordPress block editor

In the Block settings panel, you will see that there are options to change the widget’s theme, font size, colors, title, layout, and post count.

These settings are similar to the ones we’ve seen in the MonsterInsights plugin.

MonsterInsights' popular posts block settings in the WordPress block editor

The only difference is you can’t change which posts get chosen in the widget.

That said, in the Behavior Settings, it is possible to only show posts from certain categories. This way, you can make the popular post choices more tailored to your needs.

Choosing to only display posts from certain categories in the MonsterInsights popular posts widget

Once you are happy with the block settings, just click the ‘Update’ button in the post and page editor.

Here’s what the Popular Posts block looks like on our test website:

Example of what the MonsterInsights popular posts block look like on the WordPress site

Embed the Popular Posts Widget into a Sidebar

If you are using a non-block WordPress theme that has a widget-ready sidebar area, then you can add the Popular Posts widget to it.

All you have to do is go to Appearance » Widgets. Then, click the ‘+’ add widget button in the Sidebar area and look for the Popular Posts – MonsterInsights widget.

Adding the MonsterInsights popular posts widget to the sidebar area

Like in the previous method, the widget includes similar settings to customize your theme’s appearance.

What’s different is that the interface is slightly trickier to use. As you change the settings, you can’t see what the widget actually looks like. You will have to click on a different widget or another area to preview it.

If you are happy with how the widget looks, just click ‘Update’ in the top right corner.

Updating the sidebar area after adding the MonsterInsights popuplar posts widget

Make sure to go to your website to check if the sidebar looks right.

Here’s what ours looks like:

Example of the MonsterInsights popular posts widget in a sidebar

Embed the Popular Posts Widget With a Shortcode

The last option is to use a shortcode. This method is recommended if the above options don’t work for your specific use case.

In the Popular Posts Widget tab, scroll all the way down to the ‘Embed Options’ section. Then, choose ‘Display using a Shortcode’ and click the ‘Copy Shortcode’ button.

Copying the popular posts widget shortcode in MonsterInsights

After that, simply place the shortcode wherever you like. For more information, check out our guide on how to add shortcodes in WordPress.

Method 2: Display Popular WordPress Posts by Views With Code

The MonsterInsights method is the easiest way to display your most popular and best content by views in WordPress. But if you are comfortable with coding, then you can also use code to show your most popular WordPress posts.

For this method, we recommend using a code snippets plugin like WPCode, which is what we will use in this guide.

WPCode - Best WordPress Code Snippets Plugin

WPCode makes it safe to insert custom code without directly interacting with your WordPress files. Plus, since this method requires using multiple code snippets, the plugin will make managing and tracking them all much easier.

First, you need to install WPCode in WordPress. A free version of WPCode is available, but we will use the Pro version, as it comes with the features we need to insert the code in the right locations.

For a step-by-step installation guide, read our article on how to install a WordPress plugin.

Add WordPress Post Views Counter Function

Upon the plugin’s activation, you need to go to Code Snippets » + Add Snippet from the dashboard. Then, hover over ‘Add Your Custom Code (New Snippet)’ and click ‘Use snippet.’

Use snippet

Now, you are inside the WPCode code snippet editor. Before inserting any code, go ahead and add a title for the snippet.

For this first code, you can name it something like ‘WordPress Post Views Counter Function.’ This is because this first code’s purpose is to create a function for counting post views in WordPress.

Next, change the Code Type to ‘PHP Snippet.’ Note that every code snippet you will have to add from this article is in PHP.

Creating the WordPress Post Views Counter Function in WPCode

After that, you can copy and paste the following code below:

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);
    }
}
//Get rid of prefetching to keep the count accurate
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Now, just scroll down to the ‘Insertion’ section and select ‘Auto Insert’ for the Insert Method and ‘Run Everywhere’ for the Location. This works the same as inserting the code into your theme’s functions.php file.

After that, navigate to the top right side of the page and make the code active.

Then, click ‘Save Snippet.’

Choosing the insertion method and location in WPCode

At this stage, you need to add another new custom code snippet. You can name this one ‘Track Post Views Function Call.’

This code will call the function above and activate it on your single post pages.

Once you’ve done that, copy and paste the following snippet:

wpb_set_post_views(get_the_ID());

What’s different about this code snippet is you will choose the location ‘Insert After Post’ because it’s supposed to run on your single post pages.

Choosing Insert After Post as the code insertion location in WPCode

When you are done, just make the code active and save it.

Insert WordPress Post Views Tracking Hook

Now, you need to add a new code snippet that checks if the current page is a single post. If so, it will call the WordPress Post Views Counter Function to track and update the post’s view count.

This way, every time a user visits the post, its view count will get updated.

Let’s name this snippet ‘WordPress Post Views Tracking Hook.’ Then, insert the following lines of code:

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');

You can choose the insert method as ‘Auto Insert’ and the location as ‘Frontend Only.’

Same with the previous steps, just go ahead and activate the code and save the snippet.

Choosing Frontend Only as the code insertion location in WPCode

Note: If you are using a caching plugin, then this technique may not work by default. You could use the fragment caching feature that’s offered by some caching plugins like W3 Total Cache to make it work.

Add Functions to Retrieve Post Views Count and Display Most Popular Posts With View Counts

We are now in the final steps of this guide. You need to add a code snippet that retrieves and formats the number of views for a given WordPress post. This will come in handy later when displaying the list of most viewed posts.

You can name this code as ‘Retrieve Post Views Count Function’ and set the location to ‘Run Everywhere.’

Here is the code snippet:

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 View";
    }
    return $count.' Views';
}

Again, be sure to make the code active in WPCode and save it after.

Once you’ve done that, create a new code snippet again and name it ‘Display Most Popular Posts with View Counts.’ This is the code that will show your most popular posts at the bottom of your blog posts.

In the Code Preview box, insert the following snippet:

// Customize the query parameters as needed
$popularpost = new WP_Query( array(
    'posts_per_page' => 3,         // Feel free to adjust the number of posts to display
    'meta_key' => 'wpb_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
));
?>

<div class="popular-posts">
    <h2>See Our Most Popular Posts</h2> <!-- Feel free to customize the title -->
    <ul>

    <?php while ( $popularpost->have_posts() ) : $popularpost->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            - <?php echo wpb_get_post_views(get_the_ID()); ?>
        </li>
    <?php endwhile; ?>

    </ul>
</div>

<?php wp_reset_postdata(); 

As noted in the code, feel free to adjust the number of posts to display and customize the title for this section.

In the WPCode Insertion section, make sure to select ‘Insert After Post’ for the Location. Then, just make the code active and save the snippet.

All that’s left to do now is visit one of your blog posts and see if the code works. Here is what the most popular posts by views section look like on our test WordPress blog:

What the most popular posts by views section looks like made with WPCode

Expert Tip: To see if your code works without permanently changing your site, you can try WPCode’s Testing Mode.

This feature lets you add your codes like normal and only you can see what they look like on the front end. On the other side, your users will interact with your website as normal.

We hope this article helped you learn how to display popular posts by views in WordPress. You may also want to check out our article on how to display popular products in WooCommerce and our beginner’s guide to WordPress custom fields.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Display Popular Posts by Views in WordPress (2 Ways) first appeared on WPBeginner.