I have a code that informs the user that if they add X more items in cart, they will benefit from Free Shipping.
function add_custom_discount_2nd_at_50( $cart ){
$item_count = WC()->cart->get_cart_contents_count();
// $item_count = sizeof($package['contents']); -- this means total different products, no matter each of the product quantity
$totalnum = 3;
if ( $item_count < $totalnum ) {
$itemdiff = $totalnum - $item_count;
$notice = __("Add" . $itemdiff . " more products for Free Shipping.", 'xlate');
}
if ( isset($notice) ) {
wc_add_notice( $notice, 'notice' );
}
}
add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );
The code works great and the notice appears on 1) on add to cart button click, 2) on cart page and 3) on checkout page.
The only problem is that on Checkout page the notice is added twice for some reason. I even added a for ($i=0;$i>1;$i )
and still the notice is shown twice.
How can I show it only once?
CodePudding user response:
Here is the whole code that enables free shipping after X products are in the cart. The X number is fetched from wordpress admin with custom setting.
// Free shipping if products are more than X
function free_shipping_for_x_cart_items( $is_available, $package, $shipping_method ) {
$item_count = WC()->cart->get_cart_contents_count();
// $item_count = sizeof($package['contents']); -- this means total different products, no matter each of the product quantity
$totalnum = get_option('artware_settings_eshop_06');
if ( $item_count < $totalnum ) {
$is_available = false;
}
if ( $item_count >= $totalnum) {
$is_available = true;
}
return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_shipping_for_x_cart_items', 10, 3 );
function show_notice(){
$item_count = WC()->cart->get_cart_contents_count();
// $item_count = sizeof($package['contents']); -- this means total different products, no matter each of the product quantity
$totalnum = get_option('artware_settings_eshop_06');
if ( $item_count < $totalnum ) {
$itemdiff = $totalnum - $item_count;
$notice = __("Add" . $itemdiff . " more products for Free Shipping.", 'xlate');
}
if ( isset($notice) ) {
wc_add_notice( $notice, 'notice' );
}
}
// Show notice on product and cart page
function add_custom_discount_2nd_at_50( $cart ){
if ( !is_checkout() ){ show_notice(); }
}
add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );
// Show notice on checkout page
function add_custom_discount_ds50( $cart ){
if ( is_checkout() ){ show_notice(); }
}
add_action('woocommerce_before_checkout_form', 'add_custom_discount_ds50', 10, 1 );
CodePudding user response:
Could it be related to checkout page being reloaded (by user interactions or a script) and dupe notices getting rendered because of that?
If so you could check:
// Show notice on checkout page
function add_custom_discount_ds50( $cart ){
if ( is_checkout() && !isset( WC()->session->reload_checkout )) { show_notice(); }
}