我在php中为WordPress创建了一个过滤器,该过滤器在购物车中时会显示一条特殊消息。特别的消息多次显示,因为该类别的许多产品都在购物车中。如何将输出仅限为一个?这是代码:
add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
// set your special category name, slug or ID here:
$shippingclass = array( 'cut' );
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$shipping_class = get_the_terms( $values['variation_id'], 'product_shipping_class' );
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, $shippingclass ) ) {
$bool = true;
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
echo '<div class="example1"><h3>Items in your cart can be cut to save on shipping. List which items you want cut in your order notes.</h3></div>';
}
}
您在foreach
循环中回声。只需将其移到外面。另外,在找到第一个实例之后,无需继续循环,因此将$bool
设置为true
break
将其分解 add_action('woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12);
function allclean_add_checkout_content()
{
// set your special category name, slug or ID here:
$shippingclass = array('cut');
$bool = false;
foreach (WC()->cart->get_cart() as $cart_item_key => $values)
{
$shipping_class = get_the_terms($values['variation_id'], 'product_shipping_class');
if (isset($shipping_class[0]->slug) && in_array($shipping_class[0]->slug, $shippingclass))
{
$bool = true;
break;
}
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
{
echo '<div class="example1"><h3>Items in your cart can be cut to save on shipping. List which items you want cut in your order notes.</h3></div>';
}
}