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');
Edit:
meta_value value:
"a:6:{s:5:"width";s:3:"580";s:6:"**price**";s:3:"99"".
Is it possible?
2 Answers
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
a:6:{s:5:"width";s:3:"580";s:6:"price";s:3:"99"
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(
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!