Search code examples
wordpresssortingmeta-key

WP_Query - filter by multiple meta values and order by other meta values


I'm trying to query posts using WP_Query and meta_query parameters:

$args = array(
    'post_type' => 'produkty',
    'meta_query' => array(
            'relation' => 'AND',
            array(
                    'key' => 'produkt_aktywny',
                    'value' => '1',
                    'compare' => '='),
            array(
                    'key' => 'produkt_dostepnosc',
                    'value' => '1',
                    'compare' => '=')
            )
);
$query = new WP_Query( $args );

What should I add to order the results by two other keys ('produkt_kategoria' and 'produkt_cena')? There's nothing about it in WP Codex, but this:

"Do you know how to sort the query if the meta_value is an array? Write it here :)" 

According to this, I believe sorting by multiple meta values is possible.


Solution

  • I wanted to show posts from a custom post type. Order it by a custom field, and add a parameter where an other custom field was a certain value to show only a selection of posts.

    eg. select custom_posts where custom_field_a=xxxx and order by custom_field_b

    It took me a while to figure it out and when searching for it, I kept on stumbling on this post. So for all people having the same issue, here is the (simplified) code that finally did it.

            $args = array(
                'post_type' => 'my_custom_post_type',
                'meta_key' => 'custom_field_b',
                'orderby' => 'meta_value_num',
                'order' => 'DESC',
                'meta_query' => array(
                        array(
                            'key' => 'custom_field_a',
                            'value' => get_post_meta(get_the_ID(),'other_field',true),
                            'compare' => '='
                        )                   
    
                    ),
    
            ); 
            $loop2 = new WP_Query($args);
    

    You see that this is a loop in loop and therefor the value is dynamical. Of course, this could be hard coded too.

    Hope it helps someone!