BuddyDev

Modifying API Base URL Prefix for WP REST API Plugin

This post has been updated for the current WordPress REST API. Earlier, the code used was suitable for the REST API Plugin. Since the plugin has been merged into WordPress Core, the things have changed slightly.

The new URL for the endpoints contain the prefix as well as a namespace.  Here is an example endpoint

http://example.com/wp-json/wp/v2/posts/1

That will fetch the details of first post. The the above example, “wp-json” is the rest url prefix while the “wp/v2” is the namespace.

If you don’t like the default base prefix and want to change it from ‘wp-json’ to something more beautiful, the code below will help you. In the code below, I have changed the base prefix from ‘wp-json’ to ‘api’.

Once you put the above code in your theme’s functions.php or in a plugin, Please visit the Dashboard->Settings->Change your permalinks( You can restore it after saving again, we need to change it at least once to flush the rewrite rules ).

As soon as you are done with flushing the rewrite rules, you can access all the data from your new api like this

http://example.com/api/wp/v2/posts/1 etc.

Now, that is not the nicest looking url, but the version 2 of the API has made it necessary to have namespaces in the prefix(wp/v2 is the namespace here).

Want to learn about  WP REST API ? You can read the handbook here.

This post has been updated based on the comment for the current version of the WordPress API. Thank you Bryce, Gnana and Logesh.

 

6 Responses to Modifying API Base URL Prefix for WP REST API Plugin

  • Pretty useful! =)

    • Thank you Renato 🙂

    • Hi, Just want to let you know. This filter name has been changes to rest_url_prefix in recent version of WordPress.

  • The filter is now ‘rest_url_prefix’.

  • You can use the rest_url_prefix filter to change wp-json for v2, or the equivalent json_url_prefix filter to change the base for v1.

  • Thank you all of you. The post has been updated to reflect the change.

Subscribe