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);
?>
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);
?>
Share
Improve this question
edited Jan 27, 2022 at 18:25
Brett
asked Jan 27, 2022 at 14:04
BrettBrett
1871 silver badge9 bronze badges
1 Answer
Reset to default 0If 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',
),