Настройки Бесплатной доставки

Бесплатная доставка: дополнительные настройки/кастомизация

Обзор

По умолчанию WooCommerce показывает все способы доставки, подходящие для клиента и содержимого корзины. Это означает, что бесплатная доставка отображается вместе с фиксированной ценой и другими способами доставки.

Чтобы скрыть все остальные методы и показывать только бесплатную доставку, требуется либо пользовательский PHP-код, либо плагин/расширение.

Добавление кода

Перед добавлением фрагментов очистите кэш WooCommerce. Перейдите в WooCommerce > Состояние системы > Инструменты > Переходные процессы WooCommerce > Очистить переходные процессы.

Фрагменты кода

Как мне показывать только бесплатную доставку?

Следующий фрагмент скроет все другие способы доставки, если клиенту доступна бесплатная доставка.

/**
 * Hide other shipping rates when free shipping is available.
 *
 * @param array $rates Array of rates found for the package.
 *
 * @return array
 */
function fsc_hide_shipping_rates_when_free_is_available( $rates ) {
	// Go through each rate found.
	foreach ( $rates as $rate_id => $rate ) {
		// If Free Shipping is found, define it as the only rate and break out of the foreach.
		if ( 'free_shipping' === $rate->method_id ) {
			$rates = [ $rate_id => $rate ];
			break;
		}
	}
	return $rates;
}
add_filter( 'woocommerce_package_rates', 'fsc_hide_shipping_rates_when_free_is_available', 10, 1 );

Как отобразить только самовывоз и бесплатную доставку?

Следующий фрагмент кода скроет все остальные способы доставки, кроме бесплатной доставки и самовывоза, если они доступны для клиента.

/**
 * If Free Shipping is available hide other rates, excluding Local Pickup.
 *
 * @param array $rates Array of rates found for the package.
 *
 * @return array
 */
function fsc_hide_shipping_rates_when_free_is_available_excluding_local( $rates ) {
	// Define arrays to hold our Free Shipping and Local Pickup methods, if found.
	$free_shipping = [];
	$local_pickup  = [];

	// Go through each rate received.
	foreach ( $rates as $rate_id => $rate ) {
		// If either method is found, add them to their respective array.
		if ( 'free_shipping' === $rate->method_id ) {
			$free_shipping[ $rate_id ] = $rate;
			continue;
		}
		if ( 'pickup_location' === $rate->method_id ) {
			$local_pickup[ $rate_id ] = $rate;
		}
	}

	// If the free_shipping array contains a method, then merge the local_pickup into it, and overwrite the rates array.
	if ( ! empty( $free_shipping ) ) {
		$rates = array_merge( $free_shipping, $local_pickup );
	}

	return $rates;
}

add_filter( 'woocommerce_package_rates', 'fsc_hide_shipping_rates_when_free_is_available_excluding_local', 10, 1 );

Включение и отключение бесплатной доставки с помощью хуков

Если вы хотите узнать, доступна ли бесплатная доставка, это можно сделать программно. WooCommerce использует фильтр, подобный приведенному ниже:

return apply_filters( 'woocommerce_shipping_' . $this->id . '_is_available', $is_available );

Это значит, что вы можете использовать add_filter() на  woocommerce_shipping_free_shipping_is_available и получать true или false при включенной бесплатной доставке. Например, следующий фрагмент кода выведет в журнал информацию о наличии бесплатной доставки:

/**
 * Log if Free Shipping is available or not.
 *
 * @param bool $is_available If Free Shipping is available, then `true`, `false` if not.
 *
 * @return bool
 */
function fsc_free_shipping_is_available( $is_available ) {
	if ( $is_available ) {
		error_log( 'Free shipping is available' );
	} else {
		error_log( 'Free shipping is NOT available' );
	}
	return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'fsc_free_shipping_is_available', 10, 1 );

Поделиться с друзьями
Документация WooCommerce