如何修改代码在WooCommerce中排除多个分类的相关产品?
Hey there! Great question—adding a second excluded category is straightforward once you know where to adjust your existing code.
First, let’s assume your current code (the one that excludes 'workshops') looks something like this:
add_filter( 'woocommerce_related_products_query', 'exclude_specific_categories_from_related_products' ); function exclude_specific_categories_from_related_products( $query ) { // Get the current product's ID $product_id = get_the_ID(); // Get the term ID for the 'workshops' category $excluded_cat_ids = get_term_by( 'slug', 'workshops', 'product_cat' )->term_id; // Exclude the category from the related products query $query['tax_query'][] = array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $excluded_cat_ids, 'operator' => 'NOT IN', ); return $query; }
To add the 'events' category to the exclusion list, you just need to update the code to handle an array of category slugs instead of a single one. Here’s the modified version:
add_filter( 'woocommerce_related_products_query', 'exclude_specific_categories_from_related_products' ); function exclude_specific_categories_from_related_products( $query ) { // Get the current product's ID $product_id = get_the_ID(); // Define slugs of categories you want to exclude $excluded_cat_slugs = array( 'workshops', 'events' ); $excluded_cat_ids = array(); // Fetch term IDs for each excluded category slug foreach ( $excluded_cat_slugs as $slug ) { $term = get_term_by( 'slug', $slug, 'product_cat' ); if ( $term ) { $excluded_cat_ids[] = $term->term_id; } } // Only add the tax filter if we have valid category IDs if ( ! empty( $excluded_cat_ids ) ) { $query['tax_query'][] = array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $excluded_cat_ids, 'operator' => 'NOT IN', ); } return $query; }
Quick Tips:
- Double-check that
'workshops'and'events'match the exact slugs of your WooCommerce product categories (you can confirm these in Products > Categories in your WP admin). - Always edit your child theme’s
functions.php—never the parent theme, since updates will wipe your custom code. - It’s smart to back up your
functions.phpfile before making changes, just to be safe.
内容的提问来源于stack exchange,提问作者Nate
相关产品推荐
相关产品推荐

