Using WordPress ‘rest_api_register_rewrites()’ PHP function

The rest_api_register_rewrites() WordPress PHP function adds REST rewrite rules to your WordPress site.

Usage

To use the rest_api_register_rewrites() function, simply call it inside your plugin or theme file:

rest_api_register_rewrites();

Parameters

  • No parameters for this function.

More information

See WordPress Developer Resources: rest_api_register_rewrites()

This function is part of the WordPress REST API and was introduced in WordPress 4.4.0.

Examples

Adding REST API rewrite rules to your custom plugin

Create a custom plugin file, e.g. my-custom-plugin.php, and call rest_api_register_rewrites() to add REST API rewrite rules:

/*
Plugin Name: My Custom Plugin
*/

function my_custom_plugin_init() {
    rest_api_register_rewrites();
}
add_action('init', 'my_custom_plugin_init');

Adding REST API rewrite rules to your custom theme

In your theme’s functions.php file, call rest_api_register_rewrites() to add REST API rewrite rules:

function my_custom_theme_init() {
    rest_api_register_rewrites();
}
add_action('init', 'my_custom_theme_init');

Flushing rewrite rules after adding REST API rewrite rules

To ensure that the new rewrite rules are properly registered, you should flush rewrite rules after calling rest_api_register_rewrites():

function my_custom_plugin_init() {
    rest_api_register_rewrites();
    flush_rewrite_rules();
}
add_action('init', 'my_custom_plugin_init');

Deactivating REST API rewrite rules when your plugin is deactivated

When deactivating your plugin, you should remove the rewrite rules added by rest_api_register_rewrites():

function my_custom_plugin_deactivate() {
    flush_rewrite_rules();
}
register_deactivation_hook(__FILE__, 'my_custom_plugin_deactivate');

Activating REST API rewrite rules when your plugin is activated

When activating your plugin, you should add the rewrite rules by calling rest_api_register_rewrites() and then flush the rules:

function my_custom_plugin_activate() {
    rest_api_register_rewrites();
    flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'my_custom_plugin_activate');