Last active
September 5, 2024 01:55
-
-
Save danielbachhuber/8f92af4c6a8db784771c to your computer and use it in GitHub Desktop.
Disable WP REST API requests for logged out users
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'rest_authentication_errors', function( $result ) { | |
if ( ! empty( $result ) ) { | |
return $result; | |
} | |
if ( ! is_user_logged_in() ) { | |
return new WP_Error( 'restx_logged_out', 'Sorry, you must be logged in to make a request.', array( 'status' => 401 ) ); | |
} | |
return $result; | |
}); |
Hi, any idea to perform the same require authentification for 1 or more custom posts types only ? Not for all REST API request.
thx
@Nayir you can add the show_in_rest argument by user permission like
`
$show_in_rest = current_user_can( 'edit_others_posts' );
register_post_type('mycpt', array(
'show_in_rest' => $show_in_rest
));
`
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#require-authentication-for-all-requests
According to the official FAQ, it's a "good practice" to add lines 4-6; what I am missing here to protect the data?