How to Disable Delivery Dates for Specific Product Categories

With this code snippet, you can disable certain delivery dates when some products from a category are in the cart.

Here’s an example of how this might work:

If you have an online cake store, you might already know in advance that you will not be able to prepare cakes on 12/24/2022 and 12/25/2022. So you would want to prevent customers from selecting these dates when they have products from the ‘cake’ category in their cart.

If this is something you need for your store, you can accomplish it with the code snippet below:

Please replace ‘cake’ with the category of your choice in line number 13. You can add this code snippet to functions.php of your child theme or use the Code Snippet plugin.

<?php
/**
 * Iconic WDS - Set specific dates for a product category.
 *
 * @param array $dates
 * @param string $format
 * @param bool $ignore_slots
 *
 * @return array
 */
function iconic_wds_disable_dates_for_category( $dates, $format, $ignore_slots ) {
	// @todo replace 'cake' with your category.
	if ( ! iconic_check_for_cart_item_in_category( array( 'cake' ) ) || 'array' === $format ) {
		return $dates;
	}

	$disable_dates = array(
		'2022/12/24',
		'2022/12/25',
	);

	$disable_dates_formatted = array();

	foreach ( $disable_dates as $disable_date ) {
		$disable_dates_formatted[] = date_i18n( $format, strtotime( $disable_date ) );
	}

	foreach ( $dates as $index => $date ) {
		if ( in_array( $date, $disable_dates_formatted, true ) ) {
			unset( $dates[ $index ] );
		}
	}

	return array_values( $dates );
}

add_filter( 'iconic_wds_available_dates', 'iconic_wds_disable_dates_for_category', 10, 3 );

/**
 * Check cart for product in category.
 *
 * @param array $categories Categories.
 *
 * @return bool
 */
function iconic_check_for_cart_item_in_category( $categories = array() ) {
	if ( empty( $categories ) || empty( WC()->cart ) ) {
		return false;
	}

	// Set our flag to be false until we find a product in that category.
	$has_item = false;

	// Check each cart item for our category.
	foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
		$product    = $cart_item['data'];
		$product_id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();

		if ( has_term( $categories, 'product_cat', $product_id ) ) {
			$has_item = true;

			// Break because we only need one "true" to matter here.
			break;
		}
	}

	return $has_item;
}

WooCommerce Delivery Slots

Choose a delivery date and time for each order. Add a limit to the number of allowed reservations, restrict time slots to specific delivery methods, and so much more.

Was this helpful?

Please let us know if this article was useful. It is the best way to ensure our documentation is as helpful as possible.