I’m querying a series of posts in WP with the following function:
<?php
$thirtydays = date('Y/m/d', strtotime('+30 days'));
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array(
'post_type' => array('post', 'real-estate'),
'meta_key' => 'Time Available',
'meta_compare' => '<=',
'meta_value' => $thirtydays,
'paged' => $paged ));
?>
This part is working fine. It’s basically pulling all my Real Estate posts, but only returning results that have a ‘Time Available’ of 30 days or less.
I need this to also order the posts in ascending order from low to high using the data from another custom field, ‘Price.’
Whenever I add the standard 'orderby' => 'meta_value', 'meta_key' => 'Price'
it no longer shows results within 30 days.
Is there any way I can combine these two? And is it possible to add a button which re-runs the query and sorts by Price, Bedrooms, etc? Or is this too specific for WP?
I believe this will provide you want you need. It’s a class called
PostsOrderedByMetaQuery
that extendsWP_Query
and accepts new arguments'orderby_meta_key'
and ‘orderby_order'
:You would call it like this:
You can copy the
PostsOrderedByMetaQuery
class to your theme’sfunctions.php
file, or you can use it within a.php
file of a plugin you may be writing.If you want to test it quickly I’ve posted a self-contained version of the code to Gist which you can download and copy to your web server’s root as
test.php
, modify for your use case, and then request from your browser using a URL likehttp://example.com/test.php
.Hope this helps.
-Mike
P.S. This answer is very similar to an answer I just gave over at WordPress Answers, which is the sister site of StackOverflow where lots of WordPress enthusiasts like me answer questions daily. You might want to see that answer too because it has a tad more explanation and because you might want to see WordPress Answers. Hope you’ll consider posting your WordPress questions over there too in the future?
Because
'orderby' => 'meta_value'
requiresmeta_key
, and yourmeta_key
is already in use for a comparison, I don’t think you can do this.meta_key
only accepts a single value and not an array of options. This is definitely a limitation and I encourage you to open a request if you don’t find a solution.As far as the button to re-run the query, you could simply reload the page and pass a query variable to change the sort. Unfortunately you still have to solve the first part of your question.
UPDATE
You could always sort the returned array yourself using PHP.
Also, not sure what you are checking with time available but you could register a filter that may help you customize the query a bit further
add_filter('posts_where', ...);
http://codex.wordpress.org/Function_Reference/query_posts