wp query - Understanding the orderby in WP_Query?

admin2025-06-04  12

For quite a while I have been trying to query posts, with 2 different meta_queries, and order them differently. I followed the WP codex. Recently I have found out that I have been mistaken this functionality. It seems that ordering 'orderby' with multiple 'meta_key's, only works if the relation between 2 meta_queries is AND. Meaning that when queried posts have the same value for the first 'orderby' meta_key, then it orders them based on the second 'orderby' meta_key. Thus a query like below works, because of the 'relation' => 'AND', and will sort posts based on 'state_clause', if posts have the same value for 'city_clause'. Correct?

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'state_clause' => array(
            'key' => 'state',
            'compare' => 'EXISTS',
        ),
        'city_clause' => array(
            'key' => 'city',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array( 
        'city_clause' => 'ASC',
        'state_clause' => 'DESC',
    ),
) );

Question What I have been trying to do however, is order posts differently that only have one of the two custom fields. Using the example above, I have some posts with the custom field 'state' and some posts with the custom field 'city'. What I want to do is first show the posts that have the CF 'city' and order them ASC, after that I want to show the posts that have the CF 'state' and order them DESC. I have tried a code similar to the example above, but changed the relation to 'relation' => 'OR',. It queried the posts that I needed, but as I understand now it did not sort the posts as I wanted. So I am wondering if it is possible to accomplish the above, without using 2 different WP queries?

Thanks for reading.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749025598a315727.html

最新回复(0)