Different Messages Based on WooCommerce Page

≡放荡痞女 提交于 2019-12-08 04:07:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/54366556/different-messages-based-on-woocommerce-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!