如何让WordPress WooCommerce PHP函数仅作用于指定商品ID及分类
Got it, let's sort this out so your custom button only appears on the products and categories you specify. Your current code is missing proper conditional checks, which is why it's showing everywhere. Here's the breakdown and fixed solution:
What's Wrong With the Original Code
The line $productID = get_the_ID($productID,'12682, 12686'); is incorrect usage of get_the_ID() — this function doesn't take those arguments. Without any conditional logic to restrict which products trigger the button, it runs on every product page automatically.
Modified Code With Restrictions
Replace your existing function with this updated version:
/** WooCommerce custom field - 'No Thanks' Button **/ add_action('woocommerce_after_add_to_cart_button','nothanks_redirect_button'); function nothanks_redirect_button() { // Get the current WooCommerce product object (more reliable than get_the_ID() alone) global $product; if ( !$product ) return; $product_id = $product->get_id(); // 1. Define allowed product IDs (add/remove IDs as needed) $allowed_product_ids = array(12682, 12686); // 2. Define allowed product category IDs (replace with your actual category IDs) $allowed_category_ids = array(123, 456); // Check if product is in allowed ID list OR belongs to allowed category $is_allowed_product = in_array($product_id, $allowed_product_ids); $is_allowed_category = has_term($allowed_category_ids, 'product_cat', $product_id); // Get the custom redirect link from post meta $yourCustomLinkValue = get_post_meta($product_id,'nothanks_link_redirect_meta',true); // Only render the button if: product is allowed AND custom link exists if ( ($is_allowed_product || $is_allowed_category) && !empty($yourCustomLinkValue) ) { echo '<a class="button" style="margin: 0 0 0 20px" href="'.$yourCustomLinkValue.'" target="_self">No Thanks</a>'; } }
Key Changes Explained
- Reliable Product ID Fetch: Using
global $productand$product->get_id()is WooCommerce's recommended way to get the current product ID, avoiding edge cases whereget_the_ID()might fail. - Product ID Whitelist: The
$allowed_product_idsarray lets you specify exactly which products should show the button. Just add/remove IDs here. - Category Support: The
$allowed_category_idsarray lets you include entire product categories. Usehas_term()to check if the product belongs to any of these categories (works with category IDs, slugs, or names if you prefer). - Link Validation: The
!empty($yourCustomLinkValue)check ensures the button only renders if you've set a valid redirect link in the product's custom fields, avoiding broken empty links.
Optional Adjustments
- If you don't need category support, remove the
$allowed_category_idsand$is_allowed_categorylines, then simplify the final condition to:if ( $is_allowed_product && !empty($yourCustomLinkValue) ) { ... } - Move the inline
styleattribute to your theme's CSS file for cleaner code.
内容的提问来源于stack exchange,提问作者VisualWizardry
相关产品推荐
相关产品推荐

