WordPress.org

Ready to get started?Download WordPress

Forums

Query_posts restricted to one meta_value but sorted by a different meta_value (4 posts)

  1. adambundy
    Member
    Posted 4 years ago #

    Is it possible to do a query_posts and retrieve posts with a particular meta_key meta_value, but then sort the result by a different meta_key?? For instance, I have a category of products, and want to be able to restrict it to a given brand name (stored as a meta_key, which I have accomplished, but then I want to sort the result by price (also stored as a meta_key). I can only figure out how to do one or the other- not both. Thanks!!

  2. vtxyzzy
    Member
    Posted 4 years ago #

    You can do what you want by using a join filter. Code the query_posts() to select the price and sort on it. Then use code like the following (UNTESTED!) before the query to set an additional join condition on the brand.

    $brand = 'thebrandtoshow';  // Put the selected brand here
    function mam_posts_join ($join) {
       global $mam_global_join;
       if ($mam_global_join) $join .= $mam_global_join;
       return $join;
    }
    add_filter('posts_join','mam_posts_join');
    $mam_global_join = " JOIN $wpdb->postmeta as brand ON ($wpdb->posts.ID = brand.post_id AND brand.meta_key = 'brand' AND brand.meta_value ='$brand'";
  3. adambundy
    Member
    Posted 4 years ago #

    Thanks vtxyzzy, could you possibly tailor this to my case below? The else case of the if/then is where I need to restrict the output to the current value of $brandName, but need to sort by the value of meta_key 'Retail_Price'. Any tips? 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
    
    	//echo ('simple case');
    	$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
    
    	$meta_key= "product_brand";
    	$orderby= "meta_value";
    	query_posts('paged='.$paged.'&cat='.$thiscategory.'&meta_key='.$meta_key .'&orderby='.$orderby .'&order='.$order .'&meta_value='.$brandName.'');
    
    }
    ?>
  4. vtxyzzy
    Member
    Posted 4 years ago #

    You need to get it working to sort by price first. If that doesn't work, a different approach will be necessary.

Topic Closed

This topic has been closed to new replies.

About this Topic