wc_get_shipping_method_count()WC 2.6.0

Gets number of shipping methods currently enabled. Used to identify if shipping is configured.

No Hooks.

Return

Int.

Usage

wc_get_shipping_method_count( $include_legacy, $enabled_only );
$include_legacy(true|false)
Count legacy shipping methods too.
Default: false
$enabled_only(true|false)
Whether non-legacy shipping methods should be restricted to enabled ones. It doesn't affect legacy shipping methods. @since 4.3.0.
Default: false

Changelog

Since 2.6.0 Introduced.

wc_get_shipping_method_count() code WC 9.6.1

function wc_get_shipping_method_count( $include_legacy = false, $enabled_only = false ) {
	global $wpdb;

	$transient_name    = $include_legacy ? 'wc_shipping_method_count_legacy' : 'wc_shipping_method_count';
	$transient_version = WC_Cache_Helper::get_transient_version( 'shipping' );
	$transient_value   = get_transient( $transient_name );

	if ( isset( $transient_value['value'], $transient_value['version'] ) && $transient_value['version'] === $transient_version ) {
		return absint( $transient_value['value'] );
	}

	// Count activated methods that don't support shipping zones if $include_legacy is true.
	$methods      = WC()->shipping()->get_shipping_methods();
	$method_ids   = array();
	$method_count = 0;

	foreach ( $methods as $method ) {
		$method_ids[] = $method->id;

		if ( $include_legacy && isset( $method->enabled ) && 'yes' === $method->enabled && ! $method->supports( 'shipping-zones' ) ) {
			++$method_count;
		}
	}

	// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
	if ( $enabled_only ) {
		$method_count = $method_count + absint( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE is_enabled=1 AND method_id IN ('" . implode( "','", array_map( 'esc_sql', $method_ids ) ) . "')" ) );
	} else {
		$method_count = $method_count + absint( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE method_id IN ('" . implode( "','", array_map( 'esc_sql', $method_ids ) ) . "')" ) );
	}
	// phpcs:enable WordPress.DB.PreparedSQL.NotPrepared

	$transient_value = array(
		'version' => $transient_version,
		'value'   => $method_count,
	);

	set_transient( $transient_name, $transient_value, DAY_IN_SECONDS * 30 );

	return $method_count;
}