Last active
September 25, 2024 14:14
-
-
Save corsonr/7215762 to your computer and use it in GitHub Desktop.
WooCommerce: Hide Checkout Fields For Virtual Products
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'woocommerce_checkout_fields' , 'woo_remove_billing_checkout_fields' ); | |
/** | |
* Remove unwanted checkout fields | |
* | |
* @return $fields array | |
*/ | |
function woo_remove_billing_checkout_fields( $fields ) { | |
if( woo_cart_has_virtual_product() == true ) { | |
unset($fields['billing']['billing_company']); | |
unset($fields['billing']['billing_address_1']); | |
unset($fields['billing']['billing_address_2']); | |
unset($fields['billing']['billing_city']); | |
unset($fields['billing']['billing_postcode']); | |
unset($fields['billing']['billing_country']); | |
unset($fields['billing']['billing_state']); | |
unset($fields['billing']['billing_phone']); | |
unset($fields['order']['order_comments']); | |
unset($fields['billing']['billing_address_2']); | |
unset($fields['billing']['billing_postcode']); | |
unset($fields['billing']['billing_company']); | |
unset($fields['billing']['billing_city']); | |
} | |
return $fields; | |
} | |
/** | |
* Check if the cart contains virtual product | |
* | |
* @return bool | |
*/ | |
function woo_cart_has_virtual_product() { | |
global $woocommerce; | |
// By default, no virtual product | |
$has_virtual_products = false; | |
// Default virtual products number | |
$virtual_products = 0; | |
// Get all products in cart | |
$products = $woocommerce->cart->get_cart(); | |
// Loop through cart products | |
foreach( $products as $product ) { | |
// Get product ID and '_virtual' post meta | |
$product_id = $product['product_id']; | |
$is_virtual = get_post_meta( $product_id, '_virtual', true ); | |
// Update $has_virtual_product if product is virtual | |
if( $is_virtual == 'yes' ) | |
$virtual_products += 1; | |
} | |
if( count($products) == $virtual_products ) | |
$has_virtual_products = true; | |
return $has_virtual_products; | |
} |
mattpramschufer your code works, but I made some improvements for case if we have both product types in a cart
function woo_cart_has_virtual_product() {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
return $cart_item['data']->is_virtual() ? true : false;
}
return false;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not sure if it a new function, but why not use the
is_virtual()
function for the WC_Product_Simple Object ? For instance if you look at https://gist.github.com/mattpramschufer/957039753ea7a0bc3344e2f817304156 I simply have