基于特定产品类别的WooCommerce结帐消息 [英] WooCommerce checkout message based on specific product category
问题描述
WordPress商店正在使用WooCommerce,我有一个小的购买说明,我需要出现在WooCommerce Checkout上,但仅当购买某种产品时才可以。
Wordpress store is using WooCommerce, and I have a small purchase note that I need to appear on WooCommerce Checkout, but only when a certain product is being purchased.
我添加了一条自定义消息,该消息现在显示在下订单按钮下方。
但是无论购物车中的物品是什么,它都会显示出来。
I have added a custom message that now appears below the Place Order button. However its showing up no matter what is in the cart.
这是我当前使用的代码:
This is the code I currently have in place:
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>';
}
是否可以在此行之前添加一个简单的代码, 仅在购物车中使用特定类别的产品时适用吗?
Is there a simple code that I can add before this line, that makes it only apply when a certain category product is in the cart?
谢谢
推荐答案
在这里,我们检查购物车中是否有带有这个特殊类别的产品。如果满足条件(在购物车中的一项),则显示消息。
Here we check that we have a product item in cart with this special category. If the condition is matched (in one of the items of the cart), the message is displayed.
以下是代码:
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 而不是产品类别...
You can also use an array of products Ids instead of a product category...
在这种情况下,代码将有所不同:
In this case the code will be a little bit different:
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文件中(或主题),也可以在任何插件文件中。
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
此代码已经过测试,可以正常工作。
这篇关于基于特定产品类别的WooCommerce结帐消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!