Created
October 28, 2023 14:43
-
-
Save contemplate/9431ec45a1e0ac1b3b5fb61121e6e291 to your computer and use it in GitHub Desktop.
WooCommerce: Only show Terms & Conditions at checkout for specific product category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter('woocommerce_checkout_show_terms', 'remove_terms_and_conditions_checkbox_for_specific_category'); | |
function remove_terms_and_conditions_checkbox_for_specific_category($show_terms) { | |
// Check if WooCommerce is active and the cart object is available | |
if (in_array('woocommerce/woocommerce.php', get_option('active_plugins')) && WC()->cart) { | |
// Define the product category slug to check for | |
$targeted_category_slug = 'your-product-cat-slug-here'; | |
// Get the cart contents | |
$cart_items = WC()->cart->get_cart(); | |
$has_specific_category = false; | |
// Check if any cart item belongs to the specific category | |
foreach ($cart_items as $cart_item) { | |
$product = wc_get_product($cart_item['product_id']); | |
$product_categories = wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'slugs')); | |
if (in_array($targeted_category_slug, $product_categories)) { | |
$has_specific_category = true; | |
break; | |
} | |
} | |
// If a product from the specific category is in the cart, show terms & conditions checkbox | |
if ($has_specific_category) { | |
return $show_terms; | |
} | |
// If no product from the specific category is in the cart, hide terms and conditions checkbox | |
return false; | |
} | |
// If WooCommerce is not active or the cart object doesn't exist, hide terms and conditions checkbox | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Place this code in your child theme functions.php file or in the code snippets plugin.
At checkout it will check if any of the products are within a specific product category you define. If true it will show the TOS & privacy checkbox field and statement.