Block users from REST API endpoint while still grabbing data from it

Rate this post

I have created 2 REST API endpoint to store the CPT data and their custom fields:

Archive Data:
Single Business data:<ID>

Both these endpoints have been registered with the permission callbacks;

register_rest_route( 'wl/v2', '/businesses', array(
    'methods'   => WP_REST_Server::READABLE,
    'callback'  =>  'wl_businesses_posts',
    'permission_callback'   => '__return_true'

It is a business directory website where a common dashboard ( ) for each ‘business’ client exists and this dashboard page pulls in data for that ‘business’ from the Single Business data REST API endpoint above and fills the input fields on the page.

There is also another page accessible to the non-logged in visitors( ) that is common for all businesses and is a read-only page where visitors can check that business’ details. This page too pulls data from the Single Business data REST API endpoint mentioned above.

What I am trying to accomplish is that no one except the Admin should be able to peep into the Archive Data or the Single Business data endpoints directly which displays that tall JSON data, to avoid stealing info of all the businesses registered with the site. But at the same time, I would want these endpoints to be accessible by the wp_remote_retrieve_body( wp_remote_get( $url ) );code to populate the dashboard and single business info pages.

I tried this code but it obviously also blocks the requests made by the page code to pull and populate data in the pages.

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', 'You are not currently logged in.', array( 'status' => 401 ) );
    return $result;

I am not necessarily looking for a code, just the direction about how to solve this problem.

Like I said, since it is a business directory, even non logged-in users should see the archive pages and single business pages of the CPT. I’ve learned recently about the ‘permission callbacks’ in register_rest_route arguments, so how would I pass a custom ‘key’ argument in the wp_remote_get function and receive and validate it in the permission callback?



Ok I’ve managed to secure my endpoint by passing a param in the request, and only if it matches in the permission callback of the rest endpoint, then the data is retrieved:

$userData = wp_remote_retrieve_body( wp_remote_get( $url,  array(
        'body' => array(
            'param' => '1'
        'sslverify' => false,
    )  ) );

And in the register_rest_route:

'permission_callback'   => function( WP_REST_Request $request ) {
            if ( '1' == $request->get_param( 'param' ) ) {
           return true;
         } else {
       return false;

I’m so happy I wont have to use a plugin for this 😀

Leave a Reply

Your email address will not be published.

Back to top button