搜索

首页  >  问答  >  正文

如何针对特定产品隐藏 WooCommerce 的优惠券字段?

<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粉138871485P粉138871485555 天前463

全部回复(1)我来回复

  • P粉615829742

    P粉6158297422023-07-29 09:29:27

    下面的代码将处理多个产品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;
    }
    

    应该有用

    回复
    0
  • 取消回复