0

I want to order the post by 'leasenum' in my archive-shop.php. I want to filter the specific 'mall' . The result set is correct but the order is wrong. The orderby only works if I remove the 'meta_key' & 'meta_value'.

$args = array(
        'post_type'     => 'shop',
        'meta_key'      => 'mall',
        'meta_value'    =>   $getvalue,
        'posts_per_page'=>-1,
        'order'       => 'ASC',
        'orderby'     => 'leasenum',
    );
    $the_query = new WP_Query( $args );

How to make both meta_key & orderby works?

1

As you can see in the documentation, neither leasenum nor an arbitrary meta key is a valid value for orderby.

If you want to sort by a single meta value, you should set meta_key to that key, and then you can set orderby to meta_key (or meta_value_num if the value is numeric) to sort by that key. This is also described in the documentation:

Note that a meta_key=keyname must also be present in the query. Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect). Use meta_value_num instead for numeric values. You may also specify meta_type if you want to cast the meta value as a specific type. Possible values are ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’, same as in $meta_query. When using ‘meta_type’ you can also use ‘meta_value_*’ accordingly. For example, when using DATETIME as ‘meta_type’ you can use ‘meta_value_datetime’ to define order structure.

You are currently already using the meta_key property to filter the results by a value, but this can be moved to a meta_query so that you can use meta_key for sorting:

$args = array(
    'post_type'      => 'shop',
    'posts_per_page' => -1,
    'order'          => 'ASC',
    'orderby'        => 'meta_value_num',
    'meta_key'       => 'leasenum',
    'meta_query'     => array(
        array(
            'key'   => 'mall',
            'value' => $getvalue,
        ),
    ),
);

$the_query = new WP_Query( $args );
1
  • 1
    Thank you very much! It is a clear explaination! I used the code you provided and changed a little bit to 'orderby'=> 'meta_value_num', and it works! Thank you!!!
    – Muffin
    Nov 5 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.