Last active
September 20, 2021 05:28
-
-
Save tradesouthwest/e6993ebd4c57c43e31284f11a9b158bb to your computer and use it in GitHub Desktop.
allow only one category in woocommerce cart plus hide price in a cat
This file contains hidden or 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
// only allow one category to be purchased at a time | |
add_filter( 'woocommerce_add_to_cart_validation', 'dietweek_only_one_product_category_allowed', 20, 3 ); | |
function dietweek_only_one_product_category_allowed( $passed, $product_id, $quantity) { | |
// Getting the product categories term slugs in an array for the current product | |
$term_slugs = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'slugs') ); | |
// Loop through cart items | |
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){ | |
// Check if the product category of the current product don't match with a cart item | |
if( ! has_term( $term_slugs, 'product_cat', $cart_item['product_id'] ) ){ | |
// Displaying a custom notice | |
wc_add_notice( __('Only items from one product category are allowed in cart'), 'error' ); | |
// Avoid add to cart | |
return false; // exit | |
} | |
} | |
return $passed; | |
} | |
/** | |
* Bonus. Hide prices of specific category | |
*/ | |
// Specific product category archive pages | |
add_action( 'woocommerce_after_shop_loop_item_title', 'hide_loop_product_prices', 1 ); | |
function hide_loop_product_prices(){ | |
global $product; | |
if( is_product_category('PUT YOUR CATEGORY SLUG HERE') ): | |
// Hide prices | |
remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 ); | |
// Hide add-to-cart button | |
remove_action('woocommerce_after_shop_loop_item','woocommerce_template_loop_add_to_cart', 30 ); | |
endif; | |
} | |
// Single product pages | |
add_action( 'woocommerce_single_product_summary', 'hide_single_product_prices', 1 ); | |
function hide_single_product_prices(){ | |
global $product; | |
if( has_term( 'PUT YOUR CATEGORY SLUG HERE', 'product_cat', $product->get_id() ) ): | |
// Hide prices | |
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 ); | |
// Hide add-to-cart button, quantity buttons (and attributes dorpdowns for variable products) | |
if( ! $product->is_type('variable') ){ | |
remove_action('woocommerce_single_product_summary','woocommerce_template_single_add_to_cart', 30 ); | |
} else { | |
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 ); | |
} | |
endif; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment