如何针对特定产品隐藏 WooCommerce 的优惠券字段?
P粉138871485
P粉138871485 2023-07-28 11:22:20
0
1
457
<p>我正在尝试在WooCommerce购物车和结账页面中隐藏某些产品的优惠券字段。在谷歌上搜索后,我找到了一些代码可以隐藏优惠券字段,但只适用于一个产品。</p><p>我该如何在这段代码中处理多个产品:</p><p><br /></p> <pre class="brush:php;toolbar:false;">// hide coupon field on the checkout page function disable_coupon_field_on_checkout( $enabled ) { if ( is_checkout() ) { $product_id = 240790; $in_cart = false; foreach( WC()->cart->get_cart() as $cart_item ) { $product_in_cart = $cart_item['product_id']; if ( $product_in_cart === $product_id ) $in_cart = true; } if ( $in_cart === true ) { $enabled = false; } } return $enabled; } add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_on_checkout' ); // hide coupon field on the cart page function disable_coupon_field_on_cart( $enabled ) { if ( is_cart() ) { $product_id = 240790; $in_cart = false; foreach( WC()->cart->get_cart() as $cart_item ) { $product_in_cart = $cart_item['product_id']; if ( $product_in_cart === $product_id ) $in_cart = true; } if ( $in_cart === true ) { $enabled = false; } } return $enabled; } add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_on_cart' );</pre>
P粉138871485
P粉138871485

全部回复(1)
P粉615829742

下面的代码将处理多个产品ID和/或变体ID,用于购物车和结账页面,禁用这些产品的优惠券字段。

// hide coupon field on cart and checkout pages
add_filter( 'woocommerce_coupons_enabled', 'disable_coupon_field_for_specific_products' );
function disable_coupon_field_for_specific_products( $enabled ) {
    if ( ( is_checkout() && !is_wc_endpoint_url() ) || is_cart() ) {
        // here define your product IDs in the array
        $product_ids = array(240790, 240792, 240795, 240798);
        
        // Loop through cart items
        foreach( WC()->cart->get_cart() as $item ) {
            if ( count( array_intersect( [$item['product_id'], $item['variation_id']], $product_ids ) ) > 0 ) {
                return false;
            }
        }
    }
    return $enabled;
}

应该有用

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板