Automattic\WooCommerce\Utilities
RestApiUtil::attach_lazy_loaded_namespace
This is the internal function that implements the logic of self::lazy_load_namespace(). Its interface and behavior is not guaranteed. It solely exists so that $callback_filter_id does not need to be part of the public interface to self::lazy_load_namespace(). Do not call it directly.
Method of the class: RestApiUtil{}
No Hooks.
Returns
null. Nothing (null).
Usage
$RestApiUtil = new RestApiUtil(); $RestApiUtil->attach_lazy_loaded_namespace( $route_namespace, $callback, $rest_route, $callback_filter_id );
- $route_namespace(string) (required)
- The namespace to check.
- $callback(callable) (required)
- The callback to execute if the namespace should be loaded.
- $rest_route(string)
- (Optional) The REST route to check against.
Default: '' - $callback_filter_id(string)
- (Internal) Used to prevent recursive filter registration.
Default: ''
Notes
- See: self::lazy_load_namespace()
RestApiUtil::attach_lazy_loaded_namespace() RestApiUtil::attach lazy loaded namespace code WC 10.4.3
public function attach_lazy_loaded_namespace( string $route_namespace, callable $callback, string $rest_route = '', string $callback_filter_id = '' ) {
if ( '' === $rest_route && isset( $GLOBALS['wp'] ) && is_object( $GLOBALS['wp'] ) ) {
$rest_route = $GLOBALS['wp']->query_vars['rest_route'] ?? '';
}
if ( '' !== $rest_route ) {
$rest_route = trailingslashit( ltrim( $rest_route, '/' ) );
$route_namespace = trailingslashit( $route_namespace );
if ( '/' === $rest_route || str_starts_with( $rest_route, $route_namespace ) ) {
// Load all namespaces for root requests (/wp-json/) to maintain API discovery functionality.
if ( '' !== $callback_filter_id ) {
// Remove the current filter prior to the callback, to prevent recursive callback issues.
// This is crucial for APIs like wc-analytics that may callback to their own namespace when loading.
remove_filter( 'rest_pre_dispatch', $callback_filter_id, 0 );
}
call_user_func( $callback );
return;
}
}
// Register a filter to check again on rest_pre_dispatch for dynamic loading.
if ( '' === $callback_filter_id ) {
$callback_filter = function ( $filter_result, $server, $request ) use ( $route_namespace, $callback, &$callback_filter_id ) {
if ( is_callable( array( $request, 'get_route' ) ) ) {
$this->attach_lazy_loaded_namespace( $route_namespace, $callback, $request->get_route(), $callback_filter_id );
}
return $filter_result;
};
$callback_filter_id = _wp_filter_build_unique_id( 'rest_pre_dispatch', $callback_filter, 0 );
/**
* The `rest_handle_options_request()` function only works correctly if all REST API routes are registered. To ensure
* our routes are available in time, we must load the namespace before `rest_handle_options_request()` runs
* (which happens at priority 10).
*/
add_filter( 'rest_pre_dispatch', $callback_filter, 0, 3 );
}
}