Customize add to cart message in Woocommerce 3

后端 未结 1 604
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 08:25

I would like to change the \'\"[product name]\" has been added to your basket\' prompt to say \'x item(s) has/have been added to your basket\'.

This thread explains

相关标签:
1条回答
  • 2021-01-07 08:57

    Since Woocommerce 3, the filter hook wc_add_to_cart_message is obsolete and it's now replaced by wc_add_to_cart_message_html…

    The function usable variables arguments are two:

    • $message that is the outputed string message
    • $products that is an indexed array containing the product Id / quantity pairs (key / value).

    To change the default "{qty} x {product-name} has(ve) been added to your cart" message to:

    {qty} item(s) has/have been added to your basket.

    You will use the following:

    add_filter( 'wc_add_to_cart_message_html', 'custom_add_to_cart_message_html', 10, 2 );
    function custom_add_to_cart_message_html( $message, $products ) {
        $count = 0;
        foreach ( $products as $product_id => $qty ) {
            $count += $qty;
        }
        // The custom message is just below
        $added_text = sprintf( _n("%s item has %s", "%s items have %s", $count, "woocommerce" ),
            $count, __("been added to your basket.", "woocommerce") );
    
        // Output success messages
        if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
            $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
            $message   = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( $return_to ), esc_html__( 'Continue shopping', 'woocommerce' ), esc_html( $added_text ) );
        } else {
            $message   = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View cart', 'woocommerce' ), esc_html( $added_text ) );
        }
        return $message;
    }
    

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

    0 讨论(0)
提交回复
热议问题