Skip to main content
Login Join
Snippet · PHP

Disable REST API for Non-Logged-In Users

Shared by Darshit Rajyaguru · May 14, 2026 · @rest_authentication_errors

37 views
Back to Snippets

Blocks REST API access for visitors while allowing logged-in users.

add_filter( 'rest_authentication_errors', function( $result ) {
	if ( ! empty( $result ) ) {
		return $result;
	}
	if ( ! is_user_logged_in() ) {
		return new WP_Error(
			'rest_disabled',
			__( 'REST API restricted to authenticated users.' ),
			array( 'status' => 401 )
		);
	}
	return $result;
} );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments