这类似于我之前发布的一个问题 here,但我需要为一个新项目进行计算是不同的。
我需要根据购物车中商品的总数量显示通知,而不是显示购物车中任何一件商品的数量为 1 的通知。如果购物车中没有商品的数量为 1,则它不需要显示,但如果有任何项目,则需要显示。这可能吗?
答案 0 :(得分:2)
此函数循环遍历购物车商品,如果购物车商品的数量等于 1,则会显示通知并结束该功能。
function display_notice_based_on_item_quantity() {
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['quantity'] == 1 )
{
if ( is_cart() )
wc_print_notice( sprintf( __("there is an item with qunatity of 1 in the cart", "woocommerce") ), 'notice' );
break;
}
}
}
add_action( 'woocommerce_check_cart_items', 'display_notice_based_on_item_quantity' );
您可以根据需要打印通知的位置使用“woocommerce_check_cart_items”挂钩或其他购物车挂钩。
这里还有一个修改后的答案,用于排除某些类别的产品触发通知(来自评论的问题):
function display_notice_based_on_item_quantity() {
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['quantity'] == 1 )
{
$terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
foreach ( $terms as $term )
{
if ($term->slug == 'your-category-slug')
continue 2;
}
if ( is_cart() )
wc_print_notice( sprintf( __("there is an item with qunatity of 1 in the cart", "woocommerce") ), 'notice' );
break;
}
}
}
每当找到数量为 1 的产品时,就会有另一个嵌套循环遍历产品的类别,如果任何类别与您不想触发通知的类别匹配,则不会显示通知,并且外部循环继续。
不要忘记用您不想触发通知的类别的 slug 替换 'your-category-slug'。
答案 1 :(得分:0)
这是我最后用的,感谢mpx9910的回答(谢谢!):
add_action( 'woocommerce_before_cart_contents', 'display_notice_based_on_item_quantity' );
function display_notice_based_on_item_quantity() {
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['quantity'] == 1 )
{
$terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
foreach ( $terms as $term )
{
if ($term->slug == 'your-category-slug')
continue 2;
}
if ( is_cart() )
echo '<div class="cart-qty-notice">';
printf( __("Message goes here", "woocommerce"));
echo '</div>';
break;
}
}
}