I am trying to order blog posts by 'city' first and then order by 'street_name' within each city. I can't seem to get the 'street_name' to display in alphabetical order. I am using WP_Query:
<?php
$args = array(
'post_type'=> 'property',
'meta_query' => array(
array(
'relation' => 'AND' ,
array(
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
),
array(
'meta_key' => 'street_name',
'orderby' => 'meta_value',
'order' => 'ASC'
),
)
), Any ideas?
I am trying to order blog posts by 'city' first and then order by 'street_name' within each city. I can't seem to get the 'street_name' to display in alphabetical order. I am using WP_Query:
<?php
$args = array(
'post_type'=> 'property',
'meta_query' => array(
array(
'relation' => 'AND' ,
array(
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
),
array(
'meta_key' => 'street_name',
'orderby' => 'meta_value',
'order' => 'ASC'
),
)
), Any ideas?
Share Improve this question asked Dec 20, 2016 at 21:09 bhoodbhood 2572 gold badges3 silver badges9 bronze badges4 Answers
Reset to default 9meta_query
and orderby
are seperate parameters, you just put them together in an array. You will have to do one then the other.
e.g.
<?php
$args = array(
'post_type' => 'property',
'meta_query' => array(
array(
'relation' => 'AND',
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
'street_clause' => array(
'key' => 'street_name',
'compare' => 'EXISTS',
),
)
)
'orderby' => array(
'city_clause' => 'desc',
'street_clause' => 'desc',
)
)
?>
https://developer.wordpress/reference/classes/wp_query/#order-orderby-parameters
Took me awhile to figure out how to order by numeric values with multiple meta keys since you can't just use orderby meta_value_num. Instead you set the type to numeric in the meta query. This is working production code.
$meta_query = array(
'relation' => 'AND',
'query_one' => array(
'key' => '_rama_ads_type'
),
'query_two' => array(
'key' => '_rama_ads_order',
'type' => 'NUMERIC',
),
);
$order_by = array(
'query_one' => 'ASC',
'query_two' => 'DESC',
);
$query->set( 'meta_query', $meta_query );
$query->set( 'orderby', $order_by );
You need to order by specific clauses for meta_query.
This link should cover everything to help you sort out the syntax and get it working.
https://make.wordpress/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
Try this, it might help.
<?php
$args = array(
'post_type' => 'Sports',
'meta_query' => array(
array(
'key' => 'league_count',
'orderby' => 'meta_value_num', /* use this only
if the key stores number otherwise use 'meta_value' */
'order' => 'ASC'
),
array(
'key' => 'matches_count',
'orderby' => 'meta_value_num',
'order' => 'ASC'
),
),
);
$query = new WP_Query( $args );
?>