0

I have a custom field called "sale_status" and the values ("For Sale", "Sold", "Let") are displayed in a radio button in admin. Now each of them can be assigned to a single property.

Currently the query fetches the properties order by post date but I want it to be by sale_status and then date.

My code is as below--

 $args = array(
      'post_type'       => 'zoo-property',
      'posts_per_page'  => $query__per_page, 
      'post_status'     => 'publish',
      'paged'           => $query__page,            
      'meta_key'        => 'sale_status',
      'orderby'         => 'meta_value_num',
      'order'           => 'DESC',

      'meta_query' => array(
        'relation' => 'AND',
        $query__types,
        $query__locations,
        $query__statuses,
        $query__investments,
        $query__price
      )

    );


    $properties_wp_query = new WP_Query($args);
    echo "Last SQL-Query: {$properties_wp_query->request}";

But it not showing in correct order.

Any help is highly appreciated. Thanks in advance.

1 Answer 1

3

When you want to include multiple sort criterion in the same query the orderby value must be an array. See WP_Query documentation for details. Try something like this:

$args = array(
    'post_type'       => 'zoo-property',
    'posts_per_page'  => $query__per_page, 
    'post_status'     => 'publish',
    'paged'           => $query__page,            
    'meta_key'        => 'sale_status',
    'orderby'         => array( 'meta_value_num' => 'DESC', 'post_date' => 'DESC' ),
    'meta_query' => array(
        'relation' => 'AND',
        $query__types,
        $query__locations,
        $query__statuses,
        $query__investments,
        $query__price
    )
);
Sign up to request clarification or add additional context in comments.

2 Comments

You can use 'meta_value_num meta_value_num' as well. The array is needed only if you want to set a different sort order for each ordered field (this functionality was added in WP 4.0).
@Technoh Many thanks for your help. It worked like a charm. Just wondering if it is possible to show the all "For Sale" first and then all "Sold" and then all "Let"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.