问题
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 how to edit the add to cart message, but I cannot find any information about the variables which can be used.
How can I show the number of products added rather than the name?
回答1:
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.
来源:https://stackoverflow.com/questions/53837991/customize-add-to-cart-message-in-woocommerce-3