例如,有一个类别层次结构。
cat_1
- cat_1_1
- cat_1_2
cat_2
- cat_2_1
- cat_2_2
etc...我想在产品页面上显示不包括此产品的其他类别的产品。
例如,如果该产品属于cat_1_1类别,则有必要:
由父类获取当前产品类别(cat_1_1);
cat_1, cat_1_1, cat_1_2);
类似于基于类别的交叉销售。
我想我无意中找到了正确的解决方案here,但在我的例子中,由于某种原因,它返回所有类别而不排除当前产品的类别树。
$current_term = get_queried_object(); // Already a WP_Term Object
if ( $current_term->parent > 0 ) {
$siblings_ids = get_terms( array(
'taxonomy' => 'product_cat',
'parent' => $current_term->parent,
'exclude' => $current_term->term_id,
'fields' => 'ids',
) );
// Get a string of coma separated terms Ids
$siblings_list_ids = implode(',', $siblings_ids);
// Testing output
echo $siblings_list_ids;
}我会感谢你的帮助)
发布于 2021-12-17 09:33:53
您必须获得当前的产品术语,因此您可以使用get_the_terms()函数。然后可以使用tax_query排除该类别产品。试试下面的代码。
global $post;
$ids = array();
// Get the product categories
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ){
$ids[] = $term->term_id; // add term id to an array.
}
// The Query
$category_based_cross_selling = new WP_Query( array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $ids,
'operator' => 'NOT IN'
),
),
) );
$postIds = array();
if ( $category_based_cross_selling->have_posts() ):
while ( $category_based_cross_selling->have_posts() ) : $category_based_cross_selling->the_post();
endwhile;
endif;
wp_reset_query();https://stackoverflow.com/questions/70390631
复制相似问题