How can I sort by meta value? In meta value I have "price" (float).

I make this query, but always get

Sorry, no posts matched your criteria.

$posts = query_posts( $query_string . '&orderby=meta_value_num&meta_key=Notes&meta_value_num=price&order=ASC');


meta_value value:

Is it possible?


Your meta value is a serialized array.

What you're asking it to get for you is all posts with a meta with the key 'Notes' and the value 'price'. Your meta value is not 'price', though, it's


The first thing you need to do to order by price is to start using a helpful key/value structure. I assume you're using something like this to store the post meta:

update_post_meta( $post_id, 'foobar', array( 'width' => 580, 'price' => 99 ), true );

when your needs would indicate that you need to do something like this:

update_post_meta( $post_id, 'width', 580, true );
update_post_meta( $post_id, 'price', 99, true );

Once you have your meta values saved in that format, you're going to want to use a meta_query:

global $query_string;
parse_str( $query_string, $my_query );
$my_query['meta_query'] = array(
         'key' => 'price',
         'value' => 0,
         'type' => 'SIGNED',
         'compare' => '>=',
$my_query['orderby'] = 'meta_value_num';
$my_query['order'] = 'ASC';
query_posts( $my_query );

Meta queries are new in WordPress 3.1, so you'll need to be using at least that version to do this.

Let me know if you run into problems!

  • Cool man, thank you very much - saved me a lot of time! – Sagive SEO Mar 27 '12 at 0:03

Maybe this solution can help you, I needed to control posts sort by meta_key and meta_value on every request so I created a filter this way:

* Filter for every the loop request
* @param mixed $request
function request( $request ) {
    $option = $_REQUEST['mysortoption'] ? $_REQUEST['mysortoption'] : 'default';

    switch ( strtolower($option) ) {
        case 'most-viewed':
            $request['meta_key'] = 'most-viewed';
            $request['orderby'] = "meta_value";
        case 'hot':
            $request['orderby'] = 'comment_count';

    return $request;
add_filter('request', 'request');

Ok, this solution is part of a big requirement but what we're doing here is just intercepting every request, verify is there is a special sort option I added before and apply the corresponding sort by meta.

Hope this helps you.

Your Answer

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