I’m triyng to display hotels (taxonomy which i have created) by two ‘orderby’ with wp_query but i’m not success.
Results looks likes:
Hotel 1 : 2 persons 5 stars
Hotel 2 : 2 persons 4 stars
Hotel 3 : 2 persons 3 stars
Hotel 4 : 3 persons 5 stars
Hotel 5 : 5 persons 5 stars
Hotel 6: 10 persons 2 stars
Hotel 7: 10 persons 1 star
The first ‘order by’ is on the number of persons(the biggest in first) and the second ‘order by’ is on the rating in stars (so, if several hotels have the same number of persons, the hotel with the biggest stars rating would be in first).
Below my code. I have tried to add an array inside an array with meta_query but it doesn’t work.
$args=
array(
'post_type' => 'hotel',
'Services' => $Services,
'Town' => $Town,
'meta_key' => 'Number_persons',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'meta_key' => 'Rating',
'orderby' => 'meta_value',
'order' => 'DESC',
)
)
);
$the_query = new WP_Query( $args );
Thanks a lot 🙂
If you look at the Codex for
WP_Query
you will notice thatorderby
is not a valid parameter for ameta_query
, nor isorder
, and in fact nor ismeta_key
.But even if that were sorted out, I don’t think you can do what you are trying to do with
WP_Query
. Ameta_query
is aWHERE
clause element, which makes it a kind of search and I don’t think that is what you want. If all of your posts have those keys set thenEXISTS
might get you part of the way there, but it would exclude anything without one of those keys. Something like this:But ordering is still a problem and I don’t see a way around it other than a filter on
posts_orderby
.And put all together…
Again, that is only going to work if all of your posts have those meta_keys. You could use the
posts_joins
to join the meta table yourself or you could just remove theWHERE
clause with…Note that you are adding the filters and then removing it immediately after the query runs. If you want to avoid the need for that take a look at this answer for another option, or make the filters self-removing…