Order by two meta values - one is a number and the other is text

Based on multiple searches, this is the code I'm trying to sort by two different meta key values.

'meta_query' = array(
        'relation' = 'AND',
        'listing_order' = array(
            'key' = 'atsc_bod_listing_order',
            'compare' = 'EXISTS',
        ),
        'last_name' = array(
            'key' = 'atsc_bod_last_name',
            'compare' = 'EXISTS',
        ), 
    ),
    'orderby' = array( 
        'listing_order' = 'ASC',
        'last_name' = 'ASC',
),

I want to first sort by a numerical value and then if the numerical values are the same, sort by last name. This code returns no results. I'm think it has something to do with not knowing if the sort field is 'meta_value_num' or 'meta_value' but I'm not sure how/where to add that information.

Here is the full code that includes the suggestion below.

?php
        $args = array (
        'post_type'         = 'atsc_bod',
        'posts_per_page'    = -1,
        'post_status'       = 'publish',



            'meta_query' = array(
                    'relation' = 'AND',
                    'listing_order' = array(
                        'key' = 'atsc_bod_listing_order',
                        'compare' = 'EXISTS',
                        'type'    = 'NUMERIC',
                    ),
                    'last_name' = array(
                        'key' = 'atsc_bod_last_name',
                        'compare' = 'EXISTS',
                    ), 
                ),
                'orderby' = array( 
                    'listing_order' = 'ASC',
                    'last_name' = 'ASC',
            ),



        );
        $loop = new WP_Query($args);
        ?

Topic meta-value order Wordpress

Category Web


If the atsc_bod_listing_order meta is a number, then you should set the type argument to NUMERIC like so, so that the meta value is casted as a number which then gives you the correct numerical sorting:

'listing_order' => array(
    'key'     => 'atsc_bod_listing_order',
    'compare' => 'EXISTS',
    'type'    => 'NUMERIC',
),

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.