← Back to All Snippets

Disable WordPress REST API for Unauthenticated Guest Users

⚡ Target: functions.php 🔒 Tested: WP 6.6+ / PHP 8.2+ 💻 Lang: PHP
PHP (functions.php)
add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) {
        return $result;
    }
    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            __( 'REST API access is restricted to authenticated users only.', 'tipwp' ),
            [ 'status' => 401 ]
        );
    }
    return $result;
} );

Restricts public /wp-json/ user and data endpoints to authenticated users and logged-in administrators only.

← Back to All Snippets Explore Dev Tools →