How to Allow REST API Requests While Restricted Site Access is Active

If you’re developing a WordPress site and have Restricted Site Access enabled, but want to allow requests to the REST API without requiring authentication, here’s how to do that.
Filter restricted_site_access_is_restricted, and check for the presence of the rest_route key in the query_vars property of the global WordPress object. Here’s the code packaged up as a plugin; just drop it in your plugins directory and activate.

<?php
/**
 * Plugin Name: Unrestrict REST API
 * Plugin URI: https://philipnewcomer.net/2016/05/allow-rest-api-restricted-site-access/
 * Description: Allows REST API requests while Restricted Site Access is enabled.
 * Version: 0.1.0
 * Author: Philip Newcomer
 * Author URI: https://philipnewcomer.net
 */

/**
 * Filter Restricted Site Access to allow REST API requests.
 *
 * @param bool   $is_restricted Whether access is restricted.
 * @param object $wp            The WordPress object.
 *
 * @return bool Whether access should be restricted.
 */
function pn_unrestrict_rest_api( $is_restricted, $wp ) {

    if ( ! empty( $wp->query_vars['rest_route'] ) ) {
        return false;
    }

    return $is_restricted;
}
add_filter( 'restricted_site_access_is_restricted', 'pn_unrestrict_rest_api', 10, 2 );

This is also available as a gist at https://gist.github.com/philipnewcomer/16a0aacff2e073eadc4d.

Note that at the time of this writing, 10up hasn’t updated the Restricted Site Access plugin on the wordpress.org plugin repository with the latest version which is compatible with the REST API; you’ll need to use the develop branch from the plugin’s GitHub repo until the repository is updated.

Leave a Reply

Your email address will not be published. Required fields are marked *