gpt4 book ai didi

php - 在产品类别的购物车中隐藏优惠券字段

转载 作者:可可西里 更新时间:2023-11-01 00:56:55 24 4
gpt4 key购买 nike

我试图隐藏购物车中一些已排除产品的优惠券代码字段。我已经添加了一个产品类别并将此类别从优惠券使用中排除。

代码段限制了购物车,因此一次只允许使用一种产品。在这种情况下,没有必要显示排除产品的优惠券代码。验证不会让用户应用优惠券,但如果他们甚至看不到优惠券字段会更好。

这是我找到的一个片段,它可以找到一个产品类别并显示一条消息:

// Find product category
add_action( 'woocommerce_check_cart_items', 'checking_cart_items', 12 );
function checking_cart_items() {
// set your special category name, slug or ID here:
$special_cat = 'myproductcategory';
$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;
}
// Displays a message if category is found
if ($bool)
echo '<div class="checkoutdisc">A custom message displayed.</div>';

}

这是在购物车中隐藏优惠券代码的一般代码段:

// hide coupon field on cart page
function hide_coupon_field_on_cart( $enabled ) {

if ( is_cart() ) {
$enabled = false;
}

return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_cart' );

如何使这些功能协同工作?

谢谢

最佳答案

Update: Compatibility with WooComerce 3+

是的,使用这种代码组合是可能的:

add_filter( 'woocommerce_coupons_enabled', 'conditionally_hide_cart_coupon_field' );
function conditionally_hide_cart_coupon_field( $enabled ) {
// Set your special category name, slug or ID here:
$special_cat = array('clothing');
$bool = false;

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$wc_product = $cart_item['data'];
// Woocommerce compatibility
$product_id = method_exists( $wc_product, 'get_id' ) ? $wc_product->get_id() : $wc_product->id;

$main_product_id = $cart_item['variation_id'] > 0 ? $cart_item['product_id'] : $product_id;
if ( has_term( $special_cat, 'product_cat', $main_product_id ) )
$bool = true;
}

if ( $bool && is_cart() ) {
$enabled = false;
}
return $enabled;
}

自然地,这会进入您的事件子主题(或主题)的 function.php 文件或任何插件文件中。

此代码已经过测试并且可以工作。


引用资料:

关于php - 在产品类别的购物车中隐藏优惠券字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39310419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com