问题
I know that I can automatically disable shipping fields by checking "virtual" on the product submission form, but how could I by default disable shipping fields for downloadable products on Woocommerce checkout section?
回答1:
You can use the WC_Product
conditional method is_downloadable() to target downloadable products in the following 2 cases:
1) Disable checkout shipping fields
add_filter( 'woocommerce_cart_needs_shipping_address', 'filter_cart_needs_shipping_address_callback' );
function filter_cart_needs_shipping_address_callback( $needs_shipping_address ){
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
if ( $item['data']->is_downloadable() ) {
$needs_shipping_address = false;
break; // Stop the loop
}
}
return $needs_shipping_address;
}
2) Disable shipping completely (shipping methods and shipping fields)
add_filter( 'woocommerce_cart_needs_shipping', 'filter_cart_needs_shipping_address_callback' );
function filter_cart_needs_shipping_address_callback( $needs_shipping ){
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
if ( $item['data']->is_downloadable() ) {
$needs_shipping = false;
break; // Stop the loop
}
}
return $needs_shipping;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
来源:https://stackoverflow.com/questions/57778144/disable-shipping-checkout-fields-for-downloadable-products-in-woocommerce