WP/WooCommerce条件短码输出求助:按产品类别输出指定短码
Improved WooCommerce Warranty Notice by Product Category
Hey there! Great start on your code, but there's one critical issue to fix first: the is_product_category() function checks if you're viewing a category archive page, not if the current single product belongs to that category. That means your current code won't work on individual product pages at all.
Here's how to refine this to work correctly, plus make it more scalable and maintainable:
Fixed & Scalable Code
add_action( 'woocommerce_after_single_product_summary', 'add_warranty_notice', 15 ); function add_warranty_notice() { // Extra safeguard: only run on single product pages if ( ! is_product() ) return; // Get the current product object global $product; $product_id = $product->get_id(); // Create a clean mapping of category slugs to their shortcodes $category_shortcode_map = [ 'xx-slug' => '[xx-product-notice]', 'xy-slug' => '[xy-product-notice]', // Add more category-slug => shortcode pairs here as needed ]; // Loop through the mapping to find matching categories foreach ( $category_shortcode_map as $category_slug => $shortcode ) { if ( has_term( $category_slug, 'product_cat', $product_id ) ) { echo do_shortcode( $shortcode ); // Optional: Remove this line if you want to show multiple notices for products in multiple mapped categories break; } } }
Key Improvements:
- Correct Category Check: Uses
has_term()instead ofis_product_category()to verify if the current product belongs to the target category (this is the main fix for your code). - Scalable Structure: The array mapping lets you add/remove category-shortcode pairs without writing endless
elseifblocks—way easier to maintain as your store grows. - Safety First: The
is_product()check ensures the code only runs where it's supposed to (single product pages), preventing unintended execution elsewhere. - Flexible Behavior: Remove the
break;line if you want to display multiple notices for products that fall into multiple mapped categories.
Additional Tips:
- To target multiple categories for the same shortcode, pass an array to
has_term()like this:has_term( ['xx-slug', 'xz-slug'], 'product_cat', $product_id ) - Adjust the priority value (
15inadd_action) if you need to reposition the notice relative to other elements in thewoocommerce_after_single_product_summaryhook—lower numbers run earlier, higher numbers run later.
内容的提问来源于stack exchange,提问作者K-DEV
相关产品推荐
相关产品推荐

