In WooCommerce, I am using a function that show an error message and prevent to checkout, if product from one specific category is alone in cart items.
But the error message remain displayed even if cart is empty.
How can I disable this function if cart is empty?
Here is my code:
function sv_wc_prevent_checkout_for_category() {
// set the slug of the category for which we disallow checkout
$category = 'clothing';
// get the product category
$product_cat = get_term_by( 'slug', $category, 'product_cat' );
// sanity check to prevent fatals if the term doesn't exist
if ( is_wp_error( $product_cat ) ) {
return;
}
$category_name = '' . $product_cat->name . '';
// check if this category is the only thing in the cart
if ( sv_wc_is_category_alone_in_cart( $category ) ) {
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category – you must purchase a product from another category to check out.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
/**
* Checks if a cart contains exclusively products in a given category
*
* #param string $category the slug of the product category
* #return bool - true if the cart only contains the given category
*/
function sv_wc_is_category_alone_in_cart( $category ) {
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// if a product is not in our category, bail out since we know the category is not alone
if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
return false;
}
}
// if we're here, all items in the cart are in our category
return true;
}
Thanks
To avoid error message showing when cart is empty, you need to add in your first function condition ! WC()->cart->is_empty() this way:
// Check if this category is the only thing in the cart (when cart is not empty)
if ( sv_wc_is_category_alone_in_cart( $category ) && ! WC()->cart->is_empty() ) { // <= <=
So your first function code will be:
function sv_wc_prevent_checkout_for_category() {
// set the slug of the category for which we disallow checkout
$category = 'clothing';
// get the product category
$product_cat = get_term_by( 'slug', $category, 'product_cat' );
// sanity check to prevent fatals if the term doesn't exist
if ( is_wp_error( $product_cat ) ) {
return;
}
$category_name = '' . $product_cat->name . '';
// Check if this category is the only thing in the cart (when cart is not empty)
if ( sv_wc_is_category_alone_in_cart( $category ) && ! WC()->cart->is_empty() ) { // <==
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category – you must purchase a product from another category to check out.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
Related
I am trying to disable ClearPay payment method for specific product categories.
I managed to hide the ClearPay options for the shop and product page, but it still allows me to use ClearPay in the cart.
This is the code I have used:
/**
* #param bool $bool_result
* #param WC_Product $product
*/
function clearpay_ips_callback( $bool_result, $product ) {
if( has_term( array( 18, 28 ), 'product_cat' ) ) {
// do something if current product in the loop is in product category with ID 18 or 25
$bool_result = false;
}
return $bool_result;
}
add_filter( 'clearpay_is_product_supported', 'clearpay_ips_callback', 10, 2 );
Can anyone help me to stop ClearPay being available in checkout if we have products that belong to specific product category term Ids
The product Id should be specified in has_term() like:
add_filter( 'clearpay_is_product_supported', 'clearpay_ips_callback', 10, 2 );
function clearpay_ips_callback( $bool_result, $product ) {
if( has_term( array( 18, 28 ), 'product_cat', product->get_id() ) ) {
return false;
}
return $bool_result;
}
You can also try the following for cart items on checkout page:
add_filter( 'woocommerce_available_payment_gateways', 'conditional_hiding_payment_gateway', 1, 1 );
function conditional_hiding_payment_gateway( $available_gateways ) {
// Not in backend (admin)
if( is_admin() )
return $available_gateways;
$is_in_cart = false;
// Iterating through each items in cart
foreach(WC()->cart->get_cart() as $item){
if( has_term( array( 18, 28 ), 'product_cat', $item['product_id'] ) ) {
$is_in_cart = true;
break; // stop the loop
}
}
if( $is_in_cart )
unset($available_gateways['clearpay']);
}
return $available_gateways;
}
Code goes in functions.php file of the active child theme (or active theme). It should better work.
If users purchase a product on my site, I give them the option of adding a discounted product to their cart at checkout. However, users are able to remove the original product from cart and the discounted product still remains within the cart.
Is it possible to have it such that if the discounted product is the only one in the cart, then the cart should be empty? I haven't found a way to do this.
What I have tried
Currently, I use the following code from bekarice found on Github:
/**
* Renders a notice and prevents checkout if the cart
* only contains products in a specific category
*/
function sv_wc_prevent_checkout_for_category() {
// set the slug of the category for which we disallow checkout
$category = 'clothing';
// get the product category
$product_cat = get_term_by( 'slug', $category, 'product_cat' );
// sanity check to prevent fatals if the term doesn't exist
if ( is_wp_error( $product_cat ) ) {
return;
}
$category_name = '' . $product_cat->name . '';
// check if this category is the only thing in the cart
if ( sv_wc_is_category_alone_in_cart( $category ) ) {
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category – you must purchase a product from another category to check out.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
/**
* Checks if a cart contains exclusively products in a given category
*
* #param string $category the slug of the product category
* #return bool - true if the cart only contains the given category
*/
function sv_wc_is_category_alone_in_cart( $category ) {
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// if a product is not in our category, bail out since we know the category is not alone
if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
return false;
}
}
// if we're here, all items in the cart are in our category
return true;
}
But I don't think it as good a method. Basically, it doesn't allow users to checkout if cart only contains items from a certain category.
You can use the following code that will check on adding to cart your specific discounted product that cart is not empty and that it's not alone in cart, removing it from cart:
// Add to cart validation for the discounted product
add_filter( 'woocommerce_add_to_cart_validation', 'check_specific_discounted_product', 10, 3 );
function check_specific_discounted_product( $passed, $product_id, $quantity ) {
// Settings
$discounted_product_id = 53;
if( WC()->cart->is_empty() && $discounted_product_id == $product_id ) {
wc_add_notice( __("This product can't be purchased alone."), 'notice' );
return false;
}
return $passed;
}
// Removing the discounted product if it's alone in cart
add_action( 'woocommerce_before_calculate_totals', 'conditionally_remove_a_discounted_product' );
function conditionally_remove_a_discounted_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$discounted_product_id = 53;
// Initializing variables
$discounted_item_key = false;
// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// When free productis is cart
if ( in_array( $discounted_product_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
$discounted_item_key = $cart_item_key;
}
// if any other product is in cart: EXIT
else {
return;
}
}
// When the discounted product is alone in cart, remove it
if( $discounted_item_key ) {
// display notice on removal (optional)
wc_clear_notices();
wc_add_notice( __("The discounted product can't be purchased alone and has been removed."), 'notice' );
$cart->remove_cart_item( $discounted_item_key ); // Remove
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
I am using Auto add a product for cart item from specific product categories in WooCommerce answer code to auto add a free product to the cart. The code works great if the product is in a specific category but I need to add the product if it is NOT in a specific category.
I am able to add the free product if it is not in the specific category with this edit:
if( **!** has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
$matched_category = true;
}
But this does not remove the free product when the parent product is removed.
Any help would be appreciated!
Updated: Here are the changes that are required to "auto add a product in cart except for specific defined product categories (not removing the auto added product if mixed categories are in cart):
add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_except_for_product_category', 10, 1 );
function auto_add_item_except_for_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Settings
$except_terms = array('t-shirts'); // Required product category(ies)
$auto_added_id = 70; // Specific product to be added automatically
$except_found = false;
$others_found = false;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Check for product category
if( has_term( $except_terms, 'product_cat', $cart_item['product_id'] ) ) {
$except_found = true;
} else {
$others_found = true;
}
// Check if specific product is already auto added
if( $cart_item['data']->get_id() == $auto_added_id ) {
$auto_added_item_key = $cart_item_key; // keep cart item key
}
}
// If auto added product is in cart with at least an item from a the defined product category only
if ( isset($auto_added_item_key) && $except_found && ! $others_found ) {
$cart->remove_cart_item( $auto_added_item_key ); // Remove specific product
}
// If there is at least an item from others product categories and the specific product is not in cart
elseif ( ! isset($auto_added_item_key) && ! $except_found ) {
$cart->add_to_cart( $auto_added_id ); // Add specific product
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Based on: Auto add a product for cart item from specific product categories in WooCommerce
Might be able to hook into the Woo's remove item from cart hook:
function remove_free_item() {
if ( is_admin() ) {
return;
}
$product_id = 'ID_OF_FREE_ITEM';
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $cart_item_key ) {
WC()->cart->remove_cart_item( $cart_item_key );
}
}
add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $cart) {
// removed item
$line_item = $cart->removed_cart_contents[ $removed_cart_item_key ];
// removed item product id
$product_id = $line_item[ 'product_id' ];
// might need to wrap this in some check depending on your case
remove_free_item();
}
I have a code to add a product (a deposit) automatically to a customers cart, no matter what product he has chosen - with the code below inside the functions.php. This works fine.
But now, how to extend the code that this product will only be automatically added to the cart when the customer has chosen a product from a specific product category? E.g. the deposit shouldn't be added to the cart when a customer buys a gift card.
Thanks a lot!
/**
* Automatically adds product to cart on visit
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 1267; //product added automatically
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
}
}
}
You will have to use the Wordpress conditional function hast_term() in a completely different way.
The following code will auto add to cart a pre-defined product, if a product from a product category is already in cart:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_based_on_product_category', 10, 1 );
function auto_add_item_based_on_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$required_categories = array('t-shirts'); // Required product category(ies)
$added_product_id = 1267; // Specific product to be added automatically
$matched_category = false;
// Loop through cart items
foreach ( $cart->get_cart() as $item_key => $item ) {
// Check for product category
if( has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
$matched_category = true;
}
// Check if specific product is already auto added
if( $item['data']->get_id() == $added_product_id ) {
$saved_item_key = $item_key; // keep cart item key
}
}
// If specific product is already auto added but without items from product category
if ( isset($saved_item_key) && ! $matched_category ) {
$cart->remove_cart_item( $saved_item_key ); // Remove specific product
}
// If there is an item from defined product category and specific product is not in cart
elseif ( ! isset($saved_item_key) && $matched_category ) {
$cart->add_to_cart( $added_product_id ); // Add specific product
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
I'd like to stop any customer advancing to the checkout if they do not have a particular product category in their basket. I would also like to tell them with an error message that they need to add a certain product. I've found some code but cannot it to work. I've added it as a code snippet into my Wordpress install but alas it does not function and there are no error messages even though I have debugging switched on. Here is the code that I have found in Github that may need modification in order for this to work:
function sv_wc_prevent_checkout_for_category() {
// set the slug of the category for which we disallow checkout
$category = 'sibling';
// get the product category
$product_cat = get_term_by( 'slug', $category, 'product_cat' );
// sanity check to prevent fatals if the term doesn't exist
if ( is_wp_error( $product_cat ) ) {
return;
}
$category_name = '' . $product_cat->name . '';
// check if this category is the only thing in the cart
if ( sv_wc_is_category_alone_in_cart( $category ) ) {
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category – you must purchase a product from another category to check out.', $category_name ), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
/**
* Checks if a cart contains exclusively products in a given category
*
* #param string $category the slug of the product category
* #return bool - true if the cart only contains the given category
*/
function sv_wc_is_category_alone_in_cart( $category ) {
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// if a product is not in our category, bail out since we know the category is not alone
if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
return false;
}
}
// if we're here, all items in the cart are in our category
return true;
}
So I'm looking to stop checkout (with error message) if the 'sibling' category is the only item in the cart. I have a 'standard' category which must be in the basket before the customer makes it to the checkout. Hope this makes sense.
Here you have a solution that will make the trick. There is especially 2 main functions (the last ones):
The first function (N°3) display your message on cart page, when there is something in cart but not the mandatory product category. Displays also the message on the mandatory product archive pages (useful when customer get redirected from checkout, see below).
The second function (N°4) redirect customer to the product mandatory category archive pages when it tries to checkout and his cart has not that missing mandatory product category.
Define before your mandatory category slug in your_mandatory_category_slug() function.
This is the code:
// Function that define the mandatory product category
function your_mandatory_category_slug(){
// DEFINE HERE the SLUG of the needed product category
$category = 'clothing';
return $category;
}
// Conditional function that returns true if the mandatory product category is in cart
function has_mandatory_category(){
$category_needed = your_mandatory_category_slug();
$has_cat = false;
// Iterrating each item in cart and detecting…
foreach ( WC()->cart->get_cart() as $item ) {
// Detects if the needed product category is in cart items
if ( has_term($category_needed, 'product_cat', $item['product_id'] ) ) {
$has_cat = true;
break;
}
}
return $has_cat;
}
// Function that display a message if there is not in cart a mandatory product category
function mandatory_category_display_message() {
$category_needed = your_mandatory_category_slug();
// check that cart is not empty (for cart and product category archives)
if( !WC()->cart->is_empty() && ( is_cart() || is_product_category( $category_needed ) ) ){
$category_obj = get_term_by( 'slug', $category_needed, 'product_cat' );
if ( is_wp_error( $category_obj ) ) return;
// Display message when product category is not in cart items
if ( !has_mandatory_category() ) {
$category_name = $category_obj->name;
$category_url = get_term_link( $category_needed, 'product_cat' );
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( __( '<strong>Reminder:</strong> You have to add in your cart, a product from "%1$s" category, to be allowed to check out. Please return here to "%1$s" product page', 'your_theme_domain'), $category_name, $category_url ), 'error' );
}
}
}
add_action( 'woocommerce_before_main_content', 'mandatory_category_display_message', 30 ); // for product mandatory category archives pages
add_action( 'woocommerce_check_cart_items', 'mandatory_category_display_message' ); // for cat page
// Function that redirect from checkout to mandatory product category archives pages
function mandatory_category_checkout_redirect() {
// If cart is not empty on checkout page
if( !WC()->cart->is_empty() && is_checkout() ){
$category_needed = your_mandatory_category_slug();
// If missing product category => redirect to the products category page
if ( !has_mandatory_category() )
wp_redirect( get_term_link( $category_needed, 'product_cat' ) );
}
}
add_action('template_redirect', 'mandatory_category_checkout_redirect');
This goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and fully functional.
I have adapted LoicTheAztec's answer to work with 2 categories. It seems to be working. I did not adapt the text has_mandatory_categorytext function, . If you can follow the code you can diy, but I was focusing on just functionality. There is another answer here but I preferred this answer and the other was not working for me.
// Function that define the 2 mandatory product categories cat1 & cat2
function your_mandatory_category_slug(){ $category = 'cat1'; return $category; }
function your_mandatory_category_slug2(){ $category = 'cat2'; return $category; }
// Conditional function that returns true if the mandatory product category is in cart
function has_mandatory_category1(){
$category_needed = your_mandatory_category_slug();
$has_cat = false;
foreach ( WC()->cart->get_cart() as $item ) {
if ( has_term($category_needed, 'product_cat', $item['product_id'] ) ) {
$has_cat = true;
break;
}
}
return $has_cat;
}
// Conditional function that returns true if the mandatory product category is in cart
function has_mandatory_category2(){
$category_needed = your_mandatory_category_slug2();
$has_cat = false;
foreach ( WC()->cart->get_cart() as $item ) {
if ( has_term($category_needed, 'product_cat', $item['product_id'] ) ) {
$has_cat = true;
break;
}
}
return $has_cat;
}
// Function that redirect from checkout to mandatory product category archives pages
function mandatory_category_checkout_redirect() {
// If cart is not empty on checkout page
if( !WC()->cart->is_empty() && is_checkout() ){
$category_needed = your_mandatory_category_slug();
$category_needed2 = your_mandatory_category_slug2();
if ( !has_mandatory_category1() )
wp_redirect( get_term_link( $category_needed, 'product_cat' ) );
if ( !has_mandatory_category2() )
wp_redirect( get_term_link( $category_needed2, 'product_cat' ) );
}
}
add_action('template_redirect', 'mandatory_category_checkout_redirect');
Works like a charm for my Wordpress installation with Woocommerce v2.6.12.
I would like to add two mandatory product-categories, maybe 3 or 4 in the future. I tried changing:
$category = 'slug1';
to
$category = 'slug1', 'slug2';
and
$category = array('slug1','slug2');
Without success. Is there a way to make this code work with multiple slugs?