// Add page view to each post
function count_post_views() { //Store post view count in post_meta table under 'post_views_count' meta key
if(is_single() && 'post' == get_post_type()){ //Check if this is a single post. You can add validation here for post_type, etc., later
$postID = get_the_id(); //Get the current post's ID
$count_key = 'post_views_count'; //Set the meta_key to 'post_views_count'
$count = (int)get_post_meta($postID, $count_key, true); //Grab the current meta_value for the 'post_views_count' meta_key
$count +=1; //Increase the count by 1
update_post_meta($postID, $count_key, $count); //Update the 'post_views_count' meta_value with the new count
}
}
add_action('wp_head','count_post_views');
// get query
function most_popular_posts_query($query){
$query->set('meta_key','post_views_count'); //Set the post query's meta_key to 'post_views_count'
$query->set('orderby', 'meta_value'); //Order posts by the 'post_views_count'
$query->set('order','DESC'); //Order by highest count to lowest
//return
return $query; //Pass the modified query back to Elementor
}
add_action('elementor/query/most_popular_posts' , 'most_popular_posts_query');