Restrict REST API access to some pages by user role

[ad_1]

This may not be optimal, but should work for your need. Use the ‘rest_pre_echo_response’ filter. Have your callback return an appropriate message in place of the normal response whenever you need to prevent access to the actual data. WP will properly JSON encode whatever you return for this filter.

Thank you @bcworkz

I couldn’t find a good way to use the rest_pre_echo_response filter to accomplish what I need, however, I’ve searched other rest api filter and I found rest_request_before_callbacks. and I’ve tried this code:

function pgmgr_restrict_api_requests( $response, $handler, WP_REST_Request $request )
{
  global $current_user;
  $routes_require_login = null;
  foreach( pgmgr_get_page_ids_by_slug('csd') as $key => $val )
    $routes_require_login[] = '/wp/v2/pages/' . $val;
  if( PGMGR_DEBUG )
  {
    pgmgrdebug($routes_require_login,__FILE__,__LINE__,true);
    pgmgrdebug($request,__FILE__,__LINE__,true);
  }
  if ( $current_user instanceof WP_User && ! $current_user->exists() && in_array( $request->get_route(), $routes_require_login, true ) ) {
      return new WP_Error( 'rest_cannot_read', 'No permission to view this post.', 
        array( 'status' => 401 ) );
  }
  return $response;
}
add_filter( 'rest_request_before_callbacks', 'pgmgr_restrict_api_requests', 10, 3 );

It works fine when requesting wp/v2/pages/page_id, and return 401 response, but it deliver the content of page when requesting it using other methods, i.e., wp/v2/pages?slug=page_slug

Is there a method to check if some page with id is requested through rest api whatever the method, or should i check all available method to request a page through rest api and validate them to restrict the access?

It turned out that it was a misunderstanding from my part, in fact the above method doesn’t restrict page content, even in the front-end, it just redirect users, and the page’s content is still retrievable through other methods (search, feed, …etc)

I’ve ended up with delivering pages content programmatically through shortcodes where I can check permissions strictly, and the redirections are just for a good user experience.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer