Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Order By Multiple Meta Fields WordPress

  • SOLVED

I currently have the following:

new WP_Query('post_type=listings&meta_key=Asking Price&orderby=meta_value_num&order=DESC')

I would like to order the values by the meta key "Status", then "Asking Price". How do I do both?

Answers (3)

2011-03-25

AdamGold answers:

http://www.mattvarone.com/wordpress/query-multiple-meta-values/


AdamGold comments:

Or you can use this code:

$querydetails = "
SELECT wposts.*
FROM $wpdb->posts wposts
INNER
JOIN ( SELECT post_id
FROM $wpdb->postmeta wpostmeta
WHERE ( ( wpostmeta.meta_key = 'Status'
AND wpostmeta.meta_value = '$status' )
OR ( wpostmeta.meta_key = 'price'
AND wpostmeta.meta_value '$price' )
)
GROUP
BY post_id
HAVING COUNT(*) = 4 ) AS t
ON t.post_id = wposts.ID
WHERE wposts.post_status = 'publish'
AND wposts.post_type = 'listings'
ORDER
BY wposts.post_date DESC
";

$pageposts = $wpdb->get_results($querydetails, OBJECT);

2011-03-25

Sébastien | French WordpressDesigner answers:

what the possible value for "Asking Price" and for "Status" ?


Mark Daoust comments:

Asking price will be values such as $100,000, $35,000, or similar
Status will be 'offer', 'sold', 'available'


Sébastien | French WordpressDesigner comments:


<?php
$my_query = new WP_Query('post_type=listings&meta_key=Asking Price&orderby=meta_value_num&order=DESC');

while ($my_query->have_posts()) : $my_query->the_post();
$status = get_post_meta($post->ID, 'Status', true);
if ($status="offer"){the_title();}
endwhile;

while ($my_query->have_posts()) : $my_query->the_post();
$status = get_post_meta($post->ID, 'Status', true);
if ($status="sold"){the_title();}
endwhile;

while ($my_query->have_posts()) : $my_query->the_post();
$status = get_post_meta($post->ID, 'Status', true);
if ($status="avalaible"){the_title();}
endwhile;

?>


Sébastien | French WordpressDesigner comments:

i think there is a problem with orderby=meta_value_num
that's strange...

try to create 3 post with this value for Asking price : 8, 9 and 10

try with the code of yves vu. I think that the ordre will be 10, 8, 9
could you test ?

It seems that the order is 10,2,3,4,5,6,7,8,9

@Yves vu : do you look at this "bug" ?


Sébastien | French WordpressDesigner comments:

arf, what i said ?^^
my precedent post is a big mistake
sorry, i'm tired, i go to my bed !


Sébastien | French WordpressDesigner comments:

@yves vu > after testing, it seems that your solution doesn't work. We can't use two times the same argument (meta_key, orderby, order)

2011-03-25

yves vu answers:

Hi,
Please use this code:
new WP_Query('post_type=listings&meta_key=Status&orderby=meta_value&order=DESC&meta_key=Asking Price&orderby=meta_value_num&order=DESC').

You can change value "DESC" for testing.

Tnks for reading
Phucvh