Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.