How to customise the WordPress REST API URL prefix (wp-json)

Customising the WordPress REST API URL prefix (wp-json) is quite simple and can be done through a single filter, as demonstrated in the video below.

Why would you want to set a custom REST API base?

For the most part, it comes down to personal preference. You may prefer the look or brevity of /api or /wp-json. It’s not uncommon for REST API’s to start with /api as the intention is quite clear.

Personally, if I were using WordPress to build a SaaS product that offered a public API, I would prefer the API didn’t start with /wp-json — it just doesn’t feel quite as slick or clear as /api. It also might not be quite that obvious to any developer interacting with the web application who doesn’t have a background in WordPress so we can consider /api to be a little more generic and universally understood.

Code snippet to change wp-json REST API base

The following code snippet will customise the URL to suit your needs. The code will work in your theme’s functions.php file but, as I cover in the video, putting this into a configuration plugin would be a better choice as it would ensure the customisation survives any theme changes over the life of the website.

Be sure to flush your rewrite rules after adding to your site as the wp-json rewrite rules are cached in WordPress’ options table. This change will not take affect until the rewrite rules are cleared.

<?php
// This will replace the 'wp-json' REST API prefix with 'api'.
// Be sure to flush your rewrite rules for this change to work.
add_filter( 'rest_url_prefix', function () {
return 'api';
} );

About the author

Phil Kurth is a web developer living in Melbourne, Australia. Phil has a long history of WordPress development and enjoys building tools to empower others in their web design/development practice.

When not working with the web, Phil is usually spending time with his two young sons or is out hiking through the Australian bush.

Good dev stuff, delivered.

Product news, tips, and other cool things we make.

We never share your data. Read our Privacy Policy

© 2016 – 2024 Hookturn Digital. All rights reserved.