Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a category gate for showing shipping on virtual products. Basically I have products I dont want to charge shipping on and I have them in a category called gifts... but I still want a shipping address. The problem is, is that when I use the category filter I built it wont save the address in the order... if i just use...

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

It works great...

But when i put the gate on it... it wont save the values... here is the gate...

//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);
like image 910
Matt Nath Avatar asked Feb 03 '26 10:02

Matt Nath


1 Answers

There is some mistakes in your code. To get that working, you should better set your code directly in the woocommerce_cart_needs_shipping_address filter hook this way:

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;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

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.

like image 157
LoicTheAztec Avatar answered Feb 04 '26 22:02

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!