Here’s is my post which shows only those posts who has views. Views are counted using wp-view-counter plugin and show those posts as well who are categorized as trending term either they have views or not. Now the only thing which I want to achieve is to display posts by highest views to lowest views.
function my_custom_elementor_query( $query ) {
// Check if it's the Elementor post query with a specific query ID
global $wpdb;
// Construct the SQL query
$sql = "SELECT DISTINCT {$wpdb->posts}.ID FROM {$wpdb->posts}";
// Add JOIN clauses for meta and taxonomy tables
$sql .= " LEFT JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)";
$sql .= " LEFT JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$sql .= " LEFT JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id)";
$sql .= " LEFT JOIN {$wpdb->terms} ON ({$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id)";
// Add WHERE conditions
$sql .= " WHERE 1=1";
$sql .= " AND ({$wpdb->postmeta}.meta_key = 'entry_views' AND {$wpdb->postmeta}.meta_value != '')";
$sql .= " OR ({$wpdb->terms}.slug = 'trending' AND {$wpdb->term_taxonomy}.taxonomy = 'filter')";
$sql .= " OR ({$wpdb->postmeta}.meta_key = 'entry_views' AND {$wpdb->postmeta}.meta_value != '' AND {$wpdb->terms}.slug != 'trending')";
// Execute the query
$post_ids = $wpdb->get_col( $sql );
// Set post__in parameter to fetch only these posts
$query->set( 'post__in', $post_ids );
}
add_action( 'elementor/query/custom_filter', 'my_custom_elementor_query' );