根据WooCommerce 3中的产品ID定制购物车消息 [英] Customizing add-to-cart messages based on the product IDs in WooCommerce 3
问题描述
我的网站上有两个产品,想要在将不同产品添加到购物车时显示不同的消息(在消息中,我想使用HTML).现在它显示Product successfully added to cart.
我在孩子的function.php中使用了此代码,该代码正在运行,但没有提供我真正想要的.
I have two products in my website and want to display different messages (In message I want to use HTML) on adding different products to cart. Right now it displays Product successfully added to cart.
I am using this code in my child's function.php which is working but is not giving me what I exactly want.
add_filter ( 'wc_add_to_cart_message', 'wc_add_to_cart_message_filter', 10, 2 );
function wc_add_to_cart_message_filter($message, $product_id = null) {
$titles[] = get_the_title( $product_id );
$titles = array_filter( $titles );
$added_text = sprintf( _n( '%s has been successfully added to your Basket.', '%s have been added to your Basket.', sizeof( $titles ), 'woocommerce' ), wc_format_list_of_items( $titles ) );
$message = sprintf( '%s <a href="%s" class="button">%s</a>',
esc_html( $added_text ),
esc_url( wc_get_page_permalink( 'cart' ) ),
esc_html__( 'View Cart', 'woocommerce' ));
return $message;
}
推荐答案
由于WooCommerce 3 wc_add_to_cart_message
已由 wc_add_to_cart_message_html
取代,因为现在已弃用.根据产品ID(甚至产品类别)将正确的工作方式添加到购物车消息的正确方法:
Since WooCommerce 3 wc_add_to_cart_message
is replaced by wc_add_to_cart_message_html
as it's deprecated now. The correct way to get this working customizing add to cart messages based on product IDs (or even product categories):
add_filter ( 'wc_add_to_cart_message_html', 'wc_add_to_cart_message_html_filter', 10, 2 );
function wc_add_to_cart_message_html_filter( $message, $products ) {
foreach( $products as $product_id => $quantity ){
// (If needed) get the WC_Product object
$product = wc_get_product( $product_id );
// The product title
$product_title = $product->get_title();
// Set Here a product category Id, name or slug (for example, if needed)
$product_category = "Clothing";
if( has_term( 'clothing', 'product_cat', $product_id ) ){
return __("My custom message for product category \"$product_category\" for $product_title ($product_id)", "woocommerce");
}
// Set HERE your first Product ID
if( $product_id == 37 ){
return __("My custom message 1 for $product_title ($product_id)", "woocommerce");
}
// Set HERE your Second Product ID
elseif( $product_id == 40 ){
return __("My custom message 2 for $product_title ($product_id)", "woocommerce");
}
}
return $message;
}
代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.
在WooCommerce 3+中进行了测试,并且可以正常工作.
Tested in WooCommerce 3+ and works.
这篇关于根据WooCommerce 3中的产品ID定制购物车消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!