wc_rest_should_load_namespace()WC 9.2.0.

Check if a REST namespace should be loaded. Useful to maintain site performance even when lots of REST namespaces are registered.

Hooks from the function

Return

true|false. True if the namespace should be loaded, false otherwise.

Usage

wc_rest_should_load_namespace( $ns, $rest_route ): bool;
$ns(string) (required)
The namespace to check.
$rest_route(string)
(Optional) The REST route being checked.
Default: ''

Changelog

Since 9.2.0. Introduced.

wc_rest_should_load_namespace() code WC 9.4.2

function wc_rest_should_load_namespace( string $ns, string $rest_route = '' ): bool {
	if ( '' === $rest_route ) {
		$rest_route = $GLOBALS['wp']->query_vars['rest_route'] ?? '';
	}

	if ( '' === $rest_route ) {
		return true;
	}

	$rest_route = trailingslashit( ltrim( $rest_route, '/' ) );
	$ns         = trailingslashit( $ns );

	/**
	 * Known namespaces that we know are safe to not load if the request is not for them. Namespaces not in this namespace should always be loaded, because we don't know if they won't be making another internal REST request to an unloaded namespace.
	 */
	$known_namespaces = array(
		'wc/v1',
		'wc/v2',
		'wc/v3',
		'wc-telemetry',
		'wc-admin',
		'wc-analytics',
		'wc/store',
		'wc/private',
	);

	$known_namespace_request = false;
	foreach ( $known_namespaces as $known_namespace ) {
		if ( str_starts_with( $rest_route, $known_namespace ) ) {
			$known_namespace_request = true;
			break;
		}
	}

	if ( ! $known_namespace_request ) {
		return true;
	}

	/**
	 * Filters whether a namespace should be loaded.
	 *
	 * @param bool   $should_load True if the namespace should be loaded, false otherwise.
	 * @param string $ns          The namespace to check.
	 * @param string $rest_route  The REST route being checked.
	 * @param array  $known_namespaces Known namespaces that we know are safe to not load if the request is not for them.
	 *
	 * @since 9.4
	 */
	return apply_filters( 'wc_rest_should_load_namespace', str_starts_with( $rest_route, $ns ), $ns, $rest_route, $known_namespaces );
}