要概括这一点,需要检索具有特定分类法术语B的帖子所具有的所有分类法术语A。
虽然这在几个步骤和大量的帖子循环中都不是不可能的(这确实是低效的),但我认为通过SQL提高效率是合理的。
我对此的大致看法是:
/**
* Get all terms of $tax_to taxonomy that posts in $term_from of $tax_from have.
*
* @param string $tax_from taxonomy name
* @param string $term_from term slug
* @param string $tax_to taxonomy name
*
* @return array|WP_Error
*/
function get_intersected_terms( $tax_from, $term_from, $tax_to ) {
global $wpdb;
$term_from = get_term_by( \'slug\', $term_from, $tax_from );
$query = "
SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy = \'{$tax_to}\' AND term_taxonomy_id IN (
SELECT term_taxonomy_id FROM {$wpdb->term_relationships} WHERE object_id IN (
SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = {$term_from->term_taxonomy_id}
)
)
";
$term_ids = $wpdb->get_col( $query );
if( empty( $term_ids) )
return array();
return get_terms( $tax_to, array( \'include\' => $term_ids ) );
}
// example
var_dump( get_intersected_terms( \'category\', \'cat-a\', \'post_tag\' ) );