要进一步微调DevelJoe的答案,您可以从全局$wp_query
而不是做额外的WP_Query
.
// make the current query available from global variable
global $wp_query;
// helper variable
$brands = array();
// loop queried posts
foreach ( $wp_query->posts as $queried_post ) {
// check if they have terms from custom taxonomy
$current_post_brands = get_the_terms( $queried_post, \'brands\' ); // post object accepted here also, not just ID
if ( ! is_wp_error( $current_post_brands ) && $current_post_brands ) {
// push found brands to helper variable
foreach ( $current_post_brands as $current_post_brand ) {
// avoid having same brands multiple time in the helper variable
if ( ! isset( $brands[$current_post_brand->term_id] ) ) {
$brands[$current_post_brand->term_id] = $current_post_brand;
}
}
}
}
// do something with the brand terms (WP_Term)
foreach ( $brands as $brand_id => $brand_term ) {
// yay?
}
这可能是一种更快的方法,因为WP会自动缓存被查询帖子的条款——我不了解。这里将讨论这种缓存,例如,
Explanation of update_post_(meta/term)_cache<小时/>
EDIT 23.9.2020
让我再试一次。。。
一种方法是首先查询当前类别中的所有帖子。然后loop找到帖子来检查他们的品牌条款。最后说出一系列独特的品牌术语。您还可以选择将结果保存到瞬态中,以便查询和循环不会在每次页面加载时运行,从而节省一些服务器资源。
function helper_get_brands_in_category( int $cat_id ) {
$transient = get_transient( \'brands_in_category_\' . $cat_id );
if ( $transient ) {
return $transient;
}
$args = array(
\'post_type\' => \'product\',
\'posts_per_page\' => 1000, // is this enough?
\'post_status\' => \'publish\',
\'no_found_rows\' => true,
\'update_post_meta_cache\' => false, // not needed in this case
\'fields\' => \'ids\', // not all post data needed here
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'term_id\',
\'terms\' => $cat_id,
)
),
);
$query = new WP_Query( $args );
$brands = array();
foreach ($query->posts as $post_id) {
$post_brands = get_the_terms( $post_id, \'brands\' );
if ( ! is_wp_error( $post_brands ) && $post_brands ) {
foreach ( $post_brands as $post_brand ) {
if ( ! isset( $brands[$post_brand->term_id] ) ) {
$brands[$post_brand->term_id] = $post_brand;
}
}
}
}
set_transient( \'brands_in_category_\' . $cat_id, $brands, WEEK_IN_SECONDS ); // change expiration date as needed
return $brands;
}
// Usage
$brands_in_category = helper_get_brands_in_category( get_queried_object_id() );
如果您将品牌保存到瞬态中,那么您可能还希望在添加新品牌时使瞬态无效。沿着这些路线,
function clear_brands_in_category_transients( $term_id, $tt_id ) {
$product_cats = get_terms( array(
\'taxonomy\' => \'product_cat\',
\'hide_empty\' => false,
\'fields\' => \'ids\',
) );
if ( ! is_wp_error( $product_cats ) && $product_cats ) {
foreach ($product_cats as $cat_id) {
delete_transient( \'brands_in_category_\' . $cat_id );
}
}
}
add_action( \'create_brands\', \'clear_brands_in_category_transients\', 10, 2 );
我用了
create_{$taxonomy} 上钩。