WordPress商店正在使用WooCommerce,我有一个小的购买说明,我需要在WooCommerce Checkout上显示,但仅在购买某种产品时才出现。
我添加了一条自定义消息,该消息现在显示在“下订单”按钮下方。但是,无论购物车中的物品是什么,它都会显示出来。
这是我当前使用的代码:
add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
echo '<div class="checkoutdisc">Custom message appears here fine.</div>';
}
我可以在此行之前添加一个简单的代码,使它仅在购物车中有某个类别的产品时适用吗?
谢谢
在这里,我们检查购物车中是否有此特殊类别的产品。如果条件匹配(在购物车中的一项中),则显示消息。
这是代码:
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:
$special_cat = 'special_category';
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( has_term( $special_cat, 'product_cat', $item->id ) )
$bool = true;
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
}
您还可以使用一系列产品ID而不是产品类别...
在这种情况下,代码将有所不同:
add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
// set your products IDs here:
$product_ids = array( 31, 68, 87, 124);
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( in_array( $item->id, $product_ids ) )
$bool = true;
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
}
这段代码会出现在您活动的子主题(或主题)的function.php文件中,也可能出现在任何插件文件中。
此代码已经过测试并且可以工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句