这里有一个使用过滤器的替代解决方案,它不需要get\\u terms()调用
/**
* Extends WP_Query with a posts_join filter allowing you to query by taxonomy instead of tax_query using terms
* Usage: <code> $query = new Query_By_Taxonomy( array( \'posts_per_page\' => $foo, \'orderby\' => $bar ) ); </code>
*
* @class Query_By_Taxonomy
*/
class Query_By_Taxonomy 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 ) && false !== $query->posts_by_taxonomy ) {
global $wpdb;
$join .= $wpdb->prepare(
"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=%s",
$this->taxonomy );
}
return $join;
}
}
用法:
$clients_query = new Query_By_Taxonomy(
array(
\'post_type\' => \'work\',
\'posts_per_page\' => 4,
\'taxonomy\' => \'clients\',
)
);