Blocking some REST API endpoints
-
Hi
Been trying to get this to work for ages!I am creating a REACT app that uses wordpress as a backend through the rest API. I want registered users to be able to create/edit/view their own posts via the
/wp/v2/posts/POST_ID
endpoint, but for that endpoint to be hidden for everyone else and not logged in users.I figured I could achieve this if I set my registered users to “Contributor” or “Author” and used
current_user_can( 'edit_post', $post->ID )
to control access to the end points by doing something like:if ( is_user_logged_in() ) { add_filter( 'rest_authentication_errors', function( $result ) { if ( ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'rest_not_admin', 'You are not entitled to view that.', array( 'status' => 401 ) ); } return $result; }); } else { // user is logged out -block endpoints add_filter( 'rest_endpoints', function( $endpoints ){ if ( isset( $endpoints['/wp/v2/posts'] ) ) { unset( $endpoints['/wp/v2/posts'] ); } if ( isset( $endpoints['/wp/v2/posts/(?P<id>[\d]+)'] ) ) { unset( $endpoints['/wp/v2/posts/(?P<id>[\d]+)'] ); } return $endpoints; }); }
This keeps the not-logged-in users out, but it doesn’t allow logged-in users to view their own posts. If change it to
current_user_can( 'edit_posts')
logged in users can see all posts.Any idea how I could achieve this?
Many thanks!
- The topic ‘Blocking some REST API endpoints’ is closed to new replies.