在 Woocommerce 结帐中为产品类别中的特定虚拟产品启用送货地址

Enable shipping address for specific virtual products from a product category in Woocommerce checkout

我有一个类别门用于显示虚拟产品的运费。基本上我有一些我不想收取运费的产品,我把它们放在一个叫做礼物的类别中……但我仍然想要一个送货地址。问题是,当我使用我构建的类别过滤器时,它不会按顺序保存地址...如果我只使用...

add_filter( 'woocommerce_cart_needs_shipping_address', '__return_true', 50 );

效果很好...

但是当我把门放在上面时...它不会保存值...这是门...

//gifts filter
function HDM_gift_shipping() {
// set our flag to be false until we find a product in that category
$cat_check = false;

// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    $product = $cart_item['data'];

   // if cat matches gift return true
    if ( has_term( 'gift', 'product_cat', $product->id ) ) {
        $cat_check = true;
        // break because we only need one "true" to matter here
        break;
    }
}

// if a product in the cart is in our category, do something
if ( $cat_check ) {
    add_filter( 'woocommerce_cart_needs_shipping_address', '__return_true', 50 );
}

}
add_action('woocommerce_before_checkout_billing_form', 'HDM_gift_shipping', 100);

您的代码中有一些错误。要使其正常工作,您最好直接在 woocommerce_cart_needs_shipping_address 过滤器挂钩中设置您的代码,方法如下:

add_filter( 'woocommerce_cart_needs_shipping_address', 'custom_cart_needs_shipping_address', 50, 1 );
function custom_cart_needs_shipping_address( $needs_shipping_address ) {
    // Loop though cat items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( has_term( array('gift'), 'product_cat', $cart_item['product_id'] ) ) {
            // Force enable shipping address for virtual "gift" products
            return true; 
        }
    }
    return $needs_shipping_address;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

In cart, to handle Woocommerce custom taxonomies like product categories or tags when using has_term() WordPress conditional function, you need to use $cart_item['product_id'] instead of $cart_item['data']->get_id() that doesn't work for product variations.