Home > Back-end >  How to hide checkout date picker when WooCommerce cart contains a virtual product?
How to hide checkout date picker when WooCommerce cart contains a virtual product?

Time:12-15

I need to deactivate a checkout date picker generated by a plugin when a product on cart is virtual.

Here's the hook they gave for that:

 apply_filters('woocommerce_delivery_disabled_dates', $disableDates);

Based on that information, this is my code attempt:

add_filter( 'woocommerce_checkout_fields' , 'disable_dates' );
         
function disable_dates( $fields ) {
        
   $only_virtual = true;
    
   foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
      // Check if there are non-virtual products
      if ( ! $cart_item['data']->is_virtual() ) $only_virtual = false;   
   }
     
    if( $only_virtual ) {
       apply_filters(‘woocommerce_delivery_disabled_dates’, $disableDates);
     }
     
     return $fields;
}

However this does not give the desired result, any advice how to hide the checkout date picker when the cart contains a virtual product?

CodePudding user response:

The main issues is that $disabledDates is undefined - I would however change $fields to $disableDates as it makes a bit more sense. See below:

apply_filters('woocommerce_delivery_disabled_dates', $disableDates);

add_filter( 'woocommerce_checkout_fields' , 'disable_dates' );
         
function disable_dates( $disableDates ) {
        
   $only_virtual = true;
    
   foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
      // Check if there are non-virtual products
      if ( ! $cart_item['data']->is_virtual() ) $only_virtual = false;   
   }
     
    if( $only_virtual ) {
       apply_filters('woocommerce_delivery_disabled_dates', $disableDates);
     }
     
     return $disableDates;
}

The $disableDates variable is the input argument for your callback of the hook which you named $fields ( I think )

Ps. this is just a guess based on the code you posted. There is quite a bit that is not clear to me, but $disableDates in your original code clearly should have a value.

CodePudding user response:

No need to use the woocommerce_checkout_fields hook, the logic can be applied in the appropriate hook.

So you get:

function filter_woocommerce_delivery_disabled_dates( $disableDates ) {  
    // WC Cart NOT null
    if ( ! is_null( WC()->cart ) ) {
        // Loop through cart items
        foreach ( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
            // Check if there are virtual products
            if ( $cart_item['data']->is_virtual() ) {
                $disableDates = true;
                break;
            }
        }
    }
    
    return $disableDates;
}
add_filter( 'woocommerce_delivery_disabled_dates', 'filter_woocommerce_delivery_disabled_dates', 10, 1 );
  • Related