There is a hierarchy of categories, for example
cat_1
- cat_1_1
- cat_1_2
cat_2
- cat_2_1
- cat_2_2
etc...
I want to display on the product page products from other categories that do not include this product.
If, for example, the product belongs to the category cat_1_1
, then it is necessary:
cat_1_1
);cat_1, cat_1_1, cat_1_2
);Something like category-based cross-selling.
I think I stumbled upon the right solution here , but in my case, for some reason, it returns all categories without excluding the category tree of the current product.
$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;
}
I will be grateful for any help)
You have to get current product terms for that you can use the get_the_terms()
function. then you can use tax_query
to exclude that category product. try below code.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.