I'm failing at writing an Elementor $meta_query function so posts will be ordered by meta_value_num of a given key.

Each post has a numeric value for the key google_unique_page_views

My example is below:

// Custom query to order 'recommended reading' posts by populatrity
add_action( 'elementor/query/my_custom_filter', function( $query ) {
    $meta_query = $query->get( 'meta_query' );
    if ( ! $meta_query ) {
        $meta_query = [];
    $meta_query[] = [
        'order'=> 'DESC',
        'key' => 'google_unique_page_views',
        'orderby' => 'meta_value_num',
    $query->set( 'meta_query', $meta_query );   

Do I need to include the value query?

1 Answer 1


Assuming that you want to get posts with that meta key, regardless of content, and order by that meta value, you would need to set two properties.

  1. meta_query
  2. orderby

So the code, based of your question would be like this

// Custom query to order 'recommended reading' posts by populatrity
add_action('elementor/query/my_custom_filter', function ($query) {
    if (empty($meta_query = $query->get('meta_query'))) $meta_query = [];

    // add our condition to the meta_query
    $meta_query['google_unique_page_views'] = [
        'key'     => 'google_unique_page_views',
        'compare' => 'EXISTS',

    // set the new meta_query
    $query->set('meta_query', $meta_query);

    // set the new orderby
    $query->set('orderby', [
        'google_unique_page_views' => 'DESC' // or ASC, based on your needs
  • That works perfect thanks! Had to make one tweak to orderby (replace google_unique_page_views with meta_value_num) to make it work super good. Thanks again
    – JVAN
    Nov 4, 2021 at 21:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.