Restrict the REST API to Logged-In Users
Returns an authentication error for REST API requests from visitors who are not logged in, with an allowlist for routes your site needs publicly.
Opens WPIDE on
Code
add_filter( 'rest_authentication_errors', function ( $result ) {
if ( true === $result || is_wp_error( $result ) || is_user_logged_in() ) {
return $result;
}
// Route prefixes that stay public. Add the namespaces your forms, shop or plugins use.
$public = array( '/contact-form-7/', '/wc/store/', '/oembed/' );
$route = isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? (string) $GLOBALS['wp']->query_vars['rest_route'] : '';
foreach ( $public as $prefix ) {
if ( 0 === strpos( $route, $prefix ) ) {
return $result;
}
}
return new WP_Error( 'rest_login_required', 'The REST API is only available to logged-in users.', array( 'status' => rest_authorization_required_code() ) );
} );
Notes
Test forms, search and checkout after enabling. Plugins that call the REST API for visitors need their namespace in $public.
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.