【问题标题】:Hide "ship to a different address" on WooCommerce checkout page when cart only contains 1 specific product当购物车仅包含 1 个特定产品时,在 WooCommerce 结帐页面上隐藏“运送到其他地址”
【发布时间】:2021-10-05 13:20:54
【问题描述】:

我基于之前的 SO 帖子,但在我的情况下,无论购物车中有什么,“运送到其他地址”部分都会消失。

我有一个虚拟产品,当您将它添加到购物车时,它就在购物车中:

  • 收货地区不显示。

  • 如果购物车中有任何其他产品,包括其他产品。因为您现在正在运送产品,所以会出现 Ship to。

我使用的代码是:

add_filter( 'woocommerce_cart_needs_shipping_address', 'disable_checkout_shipping_address');
function disable_checkout_shipping_address( $needs_shipping_address ) {
    $products_ids = [3649];
    $found = false;
    $others_found = false;
    foreach ( WC()->cart->get_cart() as $cart_item ){
       if (in_array( $cart_item['data']->get_id(), $products_ids ) ){
            $found = true;
        } else {
            $others_found = true;
        }
    }
    if( $found && ! $others_found )
        $needs_shipping_address = true;

    return $needs_shipping_address;
}

有什么建议吗?

【问题讨论】:

    标签: php wordpress woocommerce checkout


    【解决方案1】:

    您可以使用count( WC()->cart->get_cart() )。如果特定产品在购物车中并且购物车中只有 1 个产品 = 隐藏,否则 = 显示。

    所以你得到:

    function filter_woocommerce_cart_needs_shipping_address( $needs_shipping ) {    
        // The targeted product id
        $targeted_id = 3649;
    
        // Flag
        $found = false;
    
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( in_array( $targeted_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
                $found = true;
                break;
            }
        }
        
        // True & only 1 item in cart
        if ( $found && count( WC()->cart->get_cart() ) <= 1 ) {
            $needs_shipping = false;
        }
    
        return $needs_shipping;
    }
    add_filter( 'woocommerce_cart_needs_shipping_address', 'filter_woocommerce_cart_needs_shipping_address', 10, 1 );
    

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2021-08-04
      • 1970-01-01
      • 2015-03-17
      • 2018-06-17
      • 2021-07-11
      • 2018-05-08
      • 1970-01-01
      • 2020-12-13
      相关资源
      最近更新 更多