Two Things You Might Do When Using WordPress Rest API

Two Things You Might Do When Using WordPress Rest API

The WordPress REST API is a great thing. It allows WordPress data to be broken free from PHP templates. You can consume this data with other technologies. Data can be accessed from external sources. There are a couple things you might add to the API that are not included. One is caching and the other is restricting access.



There is no cache out of the box. If your data isn’t updated frequently then you might want to cache the data. Someone could direct a bot to slam your API endpoints and kill your server. Caching the data will slow down database hits and the data will respond quickly.

I use the WP REST API CACHE plugin. The plugin adds a purge cache link to the admin bar. There are hooks so you can purge the cache with code. The only setting is a purge cache expiration time.


WordPress REST API Restriction 

Data exposed by the REST API by default isn’t private. You need to be authenticated with the API to view sensitive information. Data exposed is normal stuff like posts and pages. Meta is never exposed unless it is registered. However, plugins could add endpoints and then possibly open up data you do not want exposed. Do not install API disabler plugins that completely disable the API. Many WordPress plugins and themes are starting to use core endpoints and you could have a non-functioning site.

The WP REST API Controller plugin is my recommendation on disabling endpoints on an individual basis. This plugin doesn’t disable endpoints used by core WordPress. This is crucial for WordPress to function properly. Again, the posts and pages endpoints do not expose anything sensitive unless you are authenticated.

Another option is to only allow certain hosts to access the API. Maybe you don’t want external sites or apps from requesting the API. This would be an internal API. The filter to use is rest_pre_serve_request. The code below only allows access from the site the API is hosted on. You could use this filter for other options. I’ve used it to only allow apps that have a valid app token.

add_action( 'rest_api_init', function() {
    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ) );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );

        return $value;
}, 15 );


I wouldn’t worry too much about the API unless you are specifically creating custom API endpoints for consumption. This is when you need to consider caching and protection of data.

Leave a Reply

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