你好@daveaspi:
您想做的事情在WordPress core中很常见,但处理得不好。可能有一些方法可以在没有自定义SQL的情况下做到这一点,但我认为它们不会扩展到大量帖子。下面是我编写的一个函数get_cross_referenced_terms()
这将得到您想要的,并附有一个如何使用它的示例。
以下代码可以放置在WordPress站点的根目录中test.php
文件以查看其工作情况。然后可以复制该函数get_cross_referenced_terms()
进入你的主题functions.php
文件或放入.php
您可能正在使用的插件的文件:
<?php
include(\'wp-load.php\');
$nike = get_term_by(\'slug\',\'nike\',\'brand\'); // This here just to illustrate
$terms = get_cross_referenced_terms(array(
\'post_type\' => \'product\',
\'related_taxonomy\' => \'brand\',
\'term_id\' => $nike->term_id,
));
foreach($terms as $term) {
echo "<p>{$term->name}</p>";
}
function get_cross_referenced_terms($args) {
global $wpdb;
$args = wp_parse_args($args,array(
\'post_type\' => \'post\',
\'taxonomy\' => \'category\',
\'related_taxonomy\' => \'post_tag\',
\'term_id\' => 0,
));
extract($args);
$sql = <<<SQL
SELECT DISTINCT
{$wpdb->terms}.*,
COUNT(*) AS post_count
FROM
{$wpdb->terms}
INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->terms}.term_id={$wpdb->term_taxonomy}.term_id
INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_taxonomy}.term_taxonomy_id={$wpdb->term_relationships}.term_taxonomy_id
INNER JOIN {$wpdb->posts} ON {$wpdb->term_relationships}.object_id={$wpdb->posts}.ID
INNER JOIN {$wpdb->term_relationships} related_relationship ON {$wpdb->posts}.ID=related_relationship.object_id
INNER JOIN {$wpdb->term_taxonomy} related_term_taxonomy ON related_relationship.term_taxonomy_id=related_term_taxonomy.term_taxonomy_id
INNER JOIN {$wpdb->terms} related_terms ON related_term_taxonomy.term_id=related_terms.term_id
WHERE 1=1
AND (related_term_taxonomy.taxonomy<>{$wpdb->term_taxonomy}.taxonomy OR related_terms.term_id<>{$wpdb->terms}.term_id)
AND {$wpdb->posts}.post_type=\'%s\'
AND {$wpdb->term_taxonomy}.taxonomy=\'%s\'
AND related_term_taxonomy.taxonomy=\'%s\'
AND related_terms.term_id=%d
GROUP BY
{$wpdb->terms}.term_id
SQL;
$sql = $wpdb->prepare($sql,$post_type,$taxonomy,$related_taxonomy,$term_id);
$terms = $wpdb->get_results($sql);
return $terms;
}