Elementor Show Your Most Popular Posts

Elementor Show Your Most Popular Posts

Element.How also offers premium tutorials! Check them here:

Table of Contents

In this tutorial, I will show you how to display your most popular or most viewed posts in Elementor using custom queries and a bit of custom code.

This will allow you to showcase the posts that engage your audience the most.

You will learn how to:

  • Track unique post views using a custom meta field
  • Create an AJAX script to update post views even with caching enabled
  • Display posts sorted by view count in Elementor
  • Multiple visits from the same device will count as only one visit

Let's get started!

First, add this Elementor Most Popular Posts custom code

Add this code in a new PHP code snippet from the Code Snippets plugin, or in your child theme functions.php file.

<script> 
/* Please login to get the code 
 * The code will be for the Elementor Show Your Most Popular Posts tutorial 
 * Found at this URL https://element.how/elementor-most-popular-posts/ 
 */ 
</script>

What the code is for

The enqueue_ajax_post_view_script function is for adding the necessary JavaScript to the footer of single post pages. This JavaScript sends an AJAX request to the server every time a post is viewed, updating the view count.

By placing the AJAX in the footer, it only loads after the rest of the page, minimizing any impact on the page's load time.

It uses localStorage to be certain that the view count is only increased one time per browser / device. So if a viewer refreshes the page, it won't increase the view count.

The track_post_views_ajax function is for incrementing the view count stored in the post's meta data.

The popular_posts_by_views_query is for changing the query to sort posts by the post_views_count meta field in descending order. With this function we create a custom Elementor query.

The post_views_count_shortcode is to create the [post_views_count] shortcode, which can be used in the loop template to show how many views each post has.

Using the Elementor Custom Query Filter To Show Most Popular Posts

Now, all you need to do after you have the code running on your website is to add the Query ID to your Loop Grid, Loop Carousel, Posts or Portfolio element.

In short this will work for any element that has a "Query" tab with a "Query ID" option.

Elementor Show Your Most Popular Posts 1

Enter this there:

<script> 
/* Please login to get the code 
 * The code will be for the Elementor Show Your Most Popular Posts tutorial 
 * Found at this URL https://element.how/elementor-most-popular-posts/ 
 */ 
</script>

Using the [post_views_count] shortcode

With almost any element that will render shortcodes, simply enter the shortcode:

Elementor Show Your Most Popular Posts 2

You can have text before and after it, or you could even have an icon element of of an eye, and then a heading element with the shortcode.

Finally, enjoy your Most Viewed Posts with Elementor!

By following these steps, you can easily track post views and display the most popular posts or most viewed posts in Elementor. This method is compatible with caching plugins.

Hope you enjoy this tutorial!

If you have any questions, just ask me in the comments.

Cheers!

Element.how also provides premium tutorials showing awesome advanced designs, check them out here.

Looking for something else? Search across 2737 Elements right here:

Checkout the Elementor Addon Finder directly

4 Responses

  1. Hi thank you! Your custom code is great works.

    What if I want to reset all post values of post_views_count_shortcode? Or what if I want to change value manually in each post?

    1. Greetings!

      Add this code right below the code shared in the tutorial to achieve the following:

      1. Have a new custom field on each post, that will show in the right column, lower down, while in the block editor. This custom field is the value of the posts views, and can be edited directly.

      2. Add a new admin page under WP Admin > Settings > Reset Posts Views with a button to reset all posts views to 0.

      // Add a custom field for editing post view count in each post
      function add_post_view_count_meta_box() {
          add_meta_box(
              'post_views_count_meta_box',   // ID
              'Post Views Count',            // Title
              'display_post_views_meta_box', // Callback
              'post',                        // Post type
              'side',                        // Context (side panel)
              'high'                         // Priority
          );
      }
      add_action('add_meta_boxes', 'add_post_view_count_meta_box');
      
      // Display the editable field in the post meta box
      function display_post_views_meta_box($post) {
          $views = get_post_meta($post->ID, 'post_views_count', true);
          echo '<input type="number" name="post_views_count" value="' . esc_attr($views) . '" />';
      }
      
      // Save the custom field value when the post is saved
      function save_post_views_count_meta_box_data($post_id) {
          if (array_key_exists('post_views_count', $_POST)) {
              update_post_meta(
                  $post_id,
                  'post_views_count',
                  intval($_POST['post_views_count'])
              );
          }
      }
      add_action('save_post', 'save_post_views_count_meta_box_data');
      
      // Create an admin page under Settings to reset all post views
      function register_reset_post_views_menu() {
          add_options_page(
              'Reset Post Views',            // Page title
              'Reset Post Views',            // Menu title
              'manage_options',              // Capability
              'reset-post-views',            // Menu slug
              'reset_post_views_page'        // Callback function
          );
      }
      add_action('admin_menu', 'register_reset_post_views_menu');
      
      // Display the reset button on the settings page with JavaScript confirm dialog
      function reset_post_views_page() {
          ?>
          <div class="wrap">
              <h1>Reset All Post Views</h1>
              <form method="post" action="" onsubmit="return confirm('Are you sure you want to reset all post views?');">
                  <?php submit_button('Reset All Post Views'); ?>
              </form>
          </div>
          <?php
          if ($_SERVER['REQUEST_METHOD'] == 'POST') {
              reset_all_post_views();
          }
      }
      
      // Function to reset all post view counts
      function reset_all_post_views() {
          $posts = get_posts(array(
              'numberposts' => -1,
              'post_type' => 'post',
              'meta_key' => 'post_views_count'
          ));
      
          foreach ($posts as $post) {
              update_post_meta($post->ID, 'post_views_count', 0);
          }
          
          echo '<div class="updated notice is-dismissible"><p>All post views have been reset.</p></div>';
      }
      

      Cheers!

  2. Hi Maxime, I love you!

    I've been searching on Google search and YouTube but none of the plugins they showed were really customizable. You've shown a custom way to add this feature to anywhere in posts which is what I was looking for. It was very useful.

    I have "project" post type that I create with ACF plugin. I see Views in admin column, but I could not change the value of each post.

    If you can help me solve the problem, that would be great. Thanks alot!

    1. Greetings!

      Sorry I really don't know what the issue might be. You edited all the code to change 'post' to 'project' where needed?

Leave a Reply