Created
November 6, 2010 09:05
-
-
Save mikeschinkel/665303 to your computer and use it in GitHub Desktop.
Class to extended WordPress' 3.0.x WP_Query to allow sorting by a meta_key.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
PostsOrderedByMetaQuery class that extends WP_Query and sorts posts meta_key | |
Author: Mike Schinkel (http://mikeschinkel.com) | |
This example works, just drop into the root of your website and call directly. | |
Use the class in your plugins or themes. | |
See: http://stackoverflow.com/questions/4111255/how-to-sort-a-query-posts-function-by-custom-field-while-limiting-posts-by-ano | |
*/ | |
header('Content-type:text/plain'); | |
include "../wp-load.php"; | |
class PostsOrderedByMetaQuery extends WP_Query { | |
var $posts_ordered_by_meta = true; | |
var $orderby_order = 'ASC'; | |
var $orderby_meta_key; | |
function __construct($args=array()) { | |
add_filter('posts_join',array(&$this,'posts_join'),10,2); | |
add_filter('posts_orderby',array(&$this,'posts_orderby'),10,2); | |
$this->posts_ordered_by_meta = true; | |
$this->orderby_meta_key = $args['orderby_meta_key']; | |
unset($args['orderby_meta_key']); | |
if (!empty($args['orderby_order'])) { | |
$this->orderby_order = $args['orderby_order']; | |
unset($args['orderby_order']); | |
} | |
parent::query($args); | |
} | |
function posts_join($join,$query) { | |
if (isset($query->posts_ordered_by_meta)) { | |
global $wpdb; | |
$join .=<<<SQL | |
INNER JOIN {$wpdb->postmeta} postmeta_price ON postmeta_price.post_id={$wpdb->posts}.ID | |
AND postmeta_price.meta_key='{$this->orderby_meta_key}' | |
SQL; | |
} | |
return $join; | |
} | |
function posts_orderby($orderby,$query) { | |
if (isset($query->posts_ordered_by_meta)) { | |
global $wpdb; | |
$orderby = "postmeta_price.meta_value {$this->orderby_order}"; | |
} | |
return $orderby; | |
} | |
} | |
$thirtydays = date('Y/m/d', strtotime('+30 days')); | |
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; | |
$query = new PostsOrderedByMetaQuery(array( | |
'post_type' => array('post', 'real-estate'), | |
'meta_key' => 'Time Available', | |
'meta_compare' => '<=', | |
'meta_value' => $thirtydays, | |
'paged' => $paged, | |
'orderby_meta_key' => 'Price', | |
'orderby_order' => 'DESC', | |
)); | |
foreach($query->posts as $post) { | |
echo " {$post->post_title}\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dude you're amazing oO'