'WC show notice on add to cart in product pages
I want to add a notice that lets the customers know when they've added a product to their cart that might not be what they intended.
So when a product is added to cart, I want to check the variation selected and compare the region attribute and compare it to the other products in their cart. If the other products have different regions, I want the product page they are in to show a notice like "NOTICE: Please be aware that your other cart items are for a different region".
I've found the woocommerce_add_to_cart
hook and this passes 6 things:
$cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data
.
So all that for context, my question is: how do I show a notice on the page when they click the add to cart button if the page is already loaded?
Thank you
Solution 1:[1]
I would prefer to add notice above or bellow the add to cart button instead. But anyway here is a tested solution. Place the following function in to your active theme functions.php
function compare_product_regions_notification($message, $products) {
$cart_product_regions = array();
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_product_id = $cart_item['product_id'];
$cart_product = wc_get_product( $cart_product_id );
$cart_attr_group = $cart_product->get_attributes();
if($cart_attr_group['pa_region']):
$cart_product_regions[] .= $cart_attr_group['pa_region']['options']['0'];
endif;
}
$cart_product_regions = array_unique($cart_product_regions);
$count = count($cart_product_regions);
if ($count > 1 ):
$message .= ' <span class="warning">'.__('NOTICE: Please be aware that your other cart items are for a different region.','textdomain').'</span>';
endif;
return $message;
}
add_filter( 'wc_add_to_cart_message_html', 'compare_product_regions_notification', 10, 2 );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Martin Mirchev |