- Add this php code in the wp code snippets plugin.
- Then use this query ID in elementor posts or any other posts widget: popular_posts_filter
3- You can also use this shortcode to show views count in each post: [post_views_count]
PHP Code:
// Function to enqueue AJAX script and add it to the footer
function enqueue_ajax_post_view_script() {
if (is_single()) {
?>
<script type="text/javascript">
window.addEventListener("load", function() {
const postId = <?php echo get_the_ID(); ?>;
const ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
if (!localStorage.getItem('post_viewed_' + postId)) {
fetch(ajaxUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: new URLSearchParams({
'action': 'track_post_views',
'post_id': postId
})
}).then(response => {
if (response.ok) {
localStorage.setItem('post_viewed_' + postId, 'true');
}
});
}
});
</script>
<?php
}
}
add_action('wp_footer', 'enqueue_ajax_post_view_script', 100);
// Function to manage AJAX request and update post views
function track_post_views_ajax() {
if (isset($_POST['post_id'])) {
$post_id = intval($_POST['post_id']);
$views = get_post_meta($post_id, 'post_views_count', true);
if ($views == '') {
$views = 0;
delete_post_meta($post_id, 'post_views_count');
add_post_meta($post_id, 'post_views_count', '0');
}
$views++;
update_post_meta($post_id, 'post_views_count', $views);
}
wp_die();
}
add_action('wp_ajax_track_post_views', 'track_post_views_ajax');
add_action('wp_ajax_nopriv_track_post_views', 'track_post_views_ajax');
/**
* Filter posts to show the most popular ones based on view count.
*/
function popular_posts_by_views_query( $query ) {
$query->set( 'meta_key', 'post_views_count' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'DESC' );
}
add_action( 'elementor/query/popular_posts_filter', 'popular_posts_by_views_query' );
// Shortcode for post views count
function post_views_count_shortcode() {
global $post;
$post_id = $post->ID;
$views = get_post_meta($post_id, 'post_views_count', true);
return $views ? $views : '0';
}
add_shortcode('post_views_count', 'post_views_count_shortcode');