skip to Main Content

I am using the following code to add a notice on the cart page if the order has less than 1kg.

// Add notice on cart when order is less than 1kg
add_action('woocommerce_check_cart_items','check_cart_minweight');
 
function check_cart_minweight(){
    global $woocommerce;

    $minweight = $woocommerce->cart->cart_contents_weight;

    if( $minweight < 1 ){ 
        wc_add_notice( sprintf( __( 'You have selected %sKg, add more items, orders over 1kg get free shipping', 'woocommerce' ), $minweight ), 'success' );
    }
}

The problem is that if the customer does not get over 1kg (many times they do not) and proceeds to checkout, the notice does not clear on checkout. Any advice to prevent this?

2

Answers


  1. There are several options. For example, you can ensure that your code is not executed on the checkout page:

    function action_woocommerce_check_cart_items() {
        // NOT for checkout page
        if ( is_checkout() ) return;
    
        // Get total weight
        $total_weight = WC()->cart->get_cart_contents_weight();
    
        // Less
        if ( $total_weight < 1 ) { 
            wc_add_notice( sprintf( __( 'You have selected %sKg, add more items, orders over 1kg get free shipping', 'woocommerce' ), $total_weight ), 'notice' );
        }
    }   
    add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10 );
    

    Another option is to make sure that the checkout page cannot be reached before the condition is met:

    function action_woocommerce_check_cart_items() {
        // Get total weight
        $total_weight = WC()->cart->get_cart_contents_weight();
    
        // Less
        if ( $total_weight < 1 ) { 
            wc_add_notice( sprintf( __( 'You have selected %sKg, add more items, orders over 1kg get free shipping', 'woocommerce' ), $total_weight ), 'error' );
    
            // Remove proceed to checkout button
            remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
        }
    }   
    add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10 );
    
    Login or Signup to reply.
  2. There is a function that does this here: https://wp-kama.com/plugin/woocommerce/function/wc_clear_notices

    <?php wc_clear_notices(); ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search