In WordPress, how to order by custom field when there is more than one custom field in the query?

I am editing an existing WordPress theme that uses custom fields in a custom query. I need to edit the query so that the results are filtered by one custom field, and ordered by a second custom field.

This is what I have attempted so far:

Read More
<?php
$query_args = array();
$query_args['post_type'] = 'woo_estate';
$query_args['meta_query'] = array(
    array(
        'key' => 'on_show',
        'value' => 'true'
    ),
    array(
        'key' => 'price',
        'type' => 'numeric',
    )
);
$query_args['orderby'] = 'price';
$query_args['order'] = 'ASC';

$query_args['posts_per_page'] = $woo_options['woo_more_entries'];
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query_args['paged'] = $paged;

?>
    <?php query_posts(  $query_args ); ?>

The problem is that the results continue to be ordered by the default (date) instead of by the price custom field.

How do I get this query to order by the custom price field?

Related posts

Leave a Reply

2 comments

  1. After digging a bit in the documentation here: http://codex.wordpress.org/Class_Reference/WP_Query I was able to come up with code that accomplished what I needed.

    $query_args = array();
    $query_args['post_type'] = 'woo_estate';
    $query_args['meta_query'] = array(
        array(
            'key' => 'on_show',
            'value' => 'true'
        )
    );
    
    $query_args['meta_key'] = 'price';
    $query_args['orderby'] = 'meta_value_num';
    $query_args['order'] = 'DESC';
    
    $query_args['posts_per_page'] = $woo_options['woo_more_entries'];
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $query_args['paged'] = $paged;
    
    query_posts(    $query_args )
    
  2. To order by a custom field you have to add meta_key in your array and orderby should be meta_value or meta_value_num for numbers, so in this case it should be meta_value_num because it’s a numeric.

    $query_args['meta_key'] = 'price';
    $query_args['orderby'] = 'meta_value_num';
    $query_args['order'] = 'ASC';
    $query_args['meta_query'] = array(
        array(
            'key' => 'on_show',
            'value' => 'true'
        )
    );
    // ...
    

    Here is another answer, you may take a look at this too.