Class to extended WordPress' 3.0.x WP_Query to allow querying for all terms in a taxonomy.
<?php | |
/* | |
PostsByTaxonomy class that extends WP_Query and filters to includes all posts that have any term of a taxonomy. | |
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://wordpress.stackexchange.com/questions/3708/custom-taxonomy-wp-query-for-all-terms-in-a-taxonomy | |
http://lists.automattic.com/pipermail/wp-hackers/2010-November/035730.html | |
*/ | |
header('Content-type:text/plain'); | |
include "wp-load.php"; | |
class PostsByTaxonomy extends WP_Query { | |
var $posts_by_taxonomy; | |
var $taxonomy; | |
function __construct($args=array()) { | |
add_filter('posts_join',array(&$this,'posts_join'),10,2); | |
$this->posts_by_taxonomy = true; | |
$this->taxonomy = $args['taxonomy']; | |
unset($args['taxonomy']); | |
parent::query($args); | |
} | |
function posts_join($join,$query) { | |
if (isset($query->posts_by_taxonomy)) { | |
global $wpdb; | |
$join .=<<<SQL | |
INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_relationships}.object_id={$wpdb->posts}.ID | |
INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id={$wpdb->term_relationships}.term_taxonomy_id | |
AND {$wpdb->term_taxonomy}.taxonomy='{$this->taxonomy}' | |
SQL; | |
} | |
return $join; | |
} | |
} | |
$query = new PostsByTaxonomy(array( | |
'taxonomy' => 'category', | |
)); | |
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