Allow Only Chosen REST API Namespaces for Visitors
Blocks REST API routes for logged-out visitors except the namespaces you list (for example oEmbed, contact forms and the WooCommerce Store API), shrinking the public attack surface without breaking front-end features.
Opens WPIDE on
Code
// Namespaces visitors may use.
$wpide_public_namespaces = array( 'oembed/1.0', 'contact-form-7/v1', 'wc/store', 'wc/store/v1', 'wpide/v1', 'jetpack/v4' );
add_filter( 'rest_pre_dispatch', function ( $result, $server, $request ) use ( $wpide_public_namespaces ) {
if ( null !== $result || is_user_logged_in() ) {
return $result;
}
$route = ltrim( $request->get_route(), '/' );
if ( '' === $route ) {
return new WP_Error( 'rest_forbidden', 'The REST API index is not available.', array( 'status' => 401 ) );
}
foreach ( $wpide_public_namespaces as $namespace ) {
if ( 0 === strpos( $route, trim( $namespace, '/' ) . '/' ) || trim( $namespace, '/' ) === $route ) {
return $result;
}
}
return new WP_Error( 'rest_forbidden', 'Authentication required.', array( 'status' => 401 ) );
}, 10, 3 );
Notes
Add the namespace of any plugin feature that stops working for visitors; the namespace is the first one or two parts of the route, such as contact-form-7/v1.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.