简体   繁体   中英

How to order wp_query by taxonomy term / custom field value

How can I build a WP query with order first by a related taxonomy and secondary by post title (or custom field)?

my "tax_x" is the taxonomy with the field to order the loop my "tax_y" limits the items, it is needed by not relevant for the order and I have a custom_field_2 for the secondary-/sub-ordering of the post in the product cpt…

$product_args = array(
        'post_type' => 'product',
        'posts_per_page'    => '-1',
            //'orderby'         => 'slug',          
            'orderby'           => 'meta_value',
            'order'             => 'ASC',
            'meta_query' => array(
                array(
                    'taxonomy'  => 'tax_x',
                    'meta_key'     => 'custom_field_1',
                    ),
            ),

            'tax_query' => array(
                array(
                    'taxonomy'  => 'tax_y',
                    'field'     => 'id',
                    'terms'     => $this_term_id
                    ),

           ) 
    );
}

If you want to use order by meta_query element, you should not use orderby meta_value, you can use orderby meta_query_array_name instead.

So let's give a name to tax_x meta_query array and then use orderby that element. And if you additionally ordering by post title, then you need to use array of two elements as orderby value. Here is the example:

$product_args = array(
        'post_type' => 'product',
        'posts_per_page'    => '-1',      
            'orderby'           => array ('tax_x_meta'=>'ASC','title'=>ASC),
            'meta_query' => array(
                'tax_x_meta'=>array(
                    'value'  => 'tax_x',
                    'key'     => 'custom_field_1',
                    ),
            ),

            'tax_query' => array(
                array(
                    'taxonomy'  => 'tax_y',
                    'field'     => 'id',
                    'terms'     => $this_term_id
                    ),

           ) 
    );
}

The part "value' => 'tax_x'," is unclear of course, i didn't understand what taxonomy is doing inside meta_query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM