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

Query_posts restricted to one meta_key value, sorted by another WordPress

  • SOLVED

Im trying to display posts, restricted first by the current cateogory, then restricted to a meta_key (product_brand) specific value, but then sorted by a different meta_key's value (Retail_Price). This situation applies in the second case of the if/else shown below, where I cant figure out how to apply both filters. The 2 vars mentioned are passed in via the URL. Thanks!


<?php
$brandName= $_GET['brandName'];
$order= $_GET['order'];

if (isset($brandName)) {
} else {
$brandName = "ALL";
}

if (isset($order)) {
} else {
$order = "DESC";
}

if ($brandName=="ALL") { // NO BRAND SET - WE WANT TO JUST SORT ACCORDING TO THE $ORDER VAR

$meta_key= "Retail_Price";
$orderby= "meta_value_num";
query_posts('paged='.$paged.'&cat='.$thiscategory.'&meta_key='.$meta_key.'&orderby='.$orderby.'&order='.$order.'');

} else { // A BRAND IS SET, SO WE NEED TO DO THE FULL SHEBANG- RESTRICT TO BRAND, SORT BY $ORDER -- this part isnt working to take into account the price

$meta_key= "product_brand";
$orderby= "meta_value";
query_posts('paged='.$paged.'&cat='.$thiscategory.'&meta_key='.$meta_key .'&orderby='.$orderby .'&order='.$order .'&meta_value='.$brandName.'');

}
?>

Answers (1)

2010-07-28

Xavier Faraudo answers:

You could retrieve first the post_ids with get_posts, then query those post ids. Instead of:
query_posts('paged='.$paged.'&cat='.$thiscategory.'&meta_key='.$meta_key .'&orderby='.$orderby .'&order='.$order .'&meta_value='.$brandName.'');

...we could use something like:

$post_ids = array();
$meta_key = 'product_brand'; //retrieve by brand
$unordered_posts = get_posts('paged='.$paged.'&cat='.$thiscategory.'&meta_key='.$meta_key.'&meta_value='.$brandName);
foreach( $unordered_posts as $unordered_post ){
$post_ids[]= $unordered_post->ID;
};
query_posts( array( 'post__in' => $post_ids , 'orderby' => 'meta_value_num' , 'order' => $order , 'meta_key' => 'Retail_Price' ) );


Adam Bundy comments:

Amazing Xavier- worked like a charm. How could I display the number of results for the current query (not the number being displayed on the current page, but total #) elsewhere on the page?? Thanks much!!


Xavier Faraudo comments:

To display the total results of the global query (not just the number of posts in current page), you can access its property in this way:

global $wp_query;
$total_results = $wp_query->found_posts;

You should take into account that $wp_query must be populated before getting the number of results (quite logical, put this way :) ), which means you should use this piece of code above after the call to query_posts().
Just "echo" the value of $total results anywhere you need, and presto!