WooCommerce – Conditional Statement to Remove unwanted checkout fields

I found this gist to hide unwanted checkout fields for virtual products. How can I adjust it so it doesn’t hide the fields if there are both virtual products and physical products? I am good at writing WordPress conditional statements, but I’m having trouble understanding how to write this one.

I would appreciate any assistance.

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

}

Related posts

1 comment

  1. Add an else condition to the following code which tells it to bail out immediately if the product is not virtual.

      // Update $has_virtual_product if product is virtual
      if( $is_virtual == 'yes' )
          $virtual_products += 1;
      else
          return false; // Cart contains both type of products, bail out immediately 
    

Comments are closed.