Search code examples
phpwordpresswoocommercehook-woocommercenotice

Different Messages Based on WooCommerce Page


I am trying to alter messages displayed when adding an a product to cart and/ or updating the cart by hooking in to the woocommerce_add_message. It's not showing anything at all and I'm wondering why.

I've tried echo and I've tried return__( Here's the code:

add_filter('woocommerce_add_message', 'change_cart_message', 10);
function change_cart_message() {

    $ncst = WC()->cart->subtotal;

    if ( is_checkout() ) {
        echo 'Your new order subtotal is: '.$ncst.'. <a style="color: green;" href="#customer_details">Ready to checkout?</a>';
    }
    elseif ( is_product() ) {
        echo 'Your new order subtotal is: '.$ncst.'. <a style="color: green;" href="'.wc_get_checkout_url().'">Ready to checkout?</a>';
    }
    else {
        echo 'Your new order subtotal is: '.$ncst.'. <a style="color: green;" href="'.wc_get_checkout_url().'">Ready to checkout?</a>';
    } 
}

What am I doing wrong?


Solution

  • Important note: A filter hook has always a variable argument to be returned.

    When using a filter hook, you need always to return the filtered value argument (but not to echo it)…

    Also your code can be simplified and compacted:

    add_filter('woocommerce_add_message', 'change_cart_message', 10, 1 );
    function change_cart_message( $message ) {
    
        $subtotal = WC()->cart->subtotal;
    
        $href = is_checkout() ? '#customer_details' : wc_get_checkout_url();
    
        return sprintf(  __("Your new order subtotal is: %s. %s"), wc_price($subtotal),
            '<a class="button alt" href="'.$href.'">' . __("Ready to checkout?") . '</a>' );
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    enter image description here