Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable default routes of WP REST API

I need to disable default routes of WP REST API and add custom routes.

I found this question which helps me to find following answer.

remove_action('rest_api_init', 'create_initial_rest_routes', 99);

However this will also remove any custom content type routes. So instead you may choose to use:

add_filter('rest_endpoints', function($endpoints) {
    if ( isset( $endpoints['/wp/v2/users'] ) ) {
        unset( $endpoints['/wp/v2/users'] );
    }
    // etc
});

But from that way I need to know all the default routes and remove one by one which is not a cleanest way to do.

I would like to know whether there is any cleaner way to achieve that ?

UPDATE 1 :

As per the Chris's suggestion I would add more details to question.

Currently I am using rest_api_init filter to add my custom routes by using register_rest_route method as per the below code which I found on this article.

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/sample/', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

function my_awesome_func( $data ) {
  return 'somthing';
}

The custom route works well, but unfortunately I can't disable the default routes such as /wp/v2/posts.

My question :

How to unset/disable the default routes while using the rest_api_init filter to register new custom routes ?

like image 203
Janith Chinthana Avatar asked Mar 13 '17 06:03

Janith Chinthana


1 Answers

As per the other question, this is the only "clean" way to do it currently. The cleanest way to approach things in Wordpress is by using filters and/or actions - this allows you to interact with core without making changes in core.

By tapping into filters/actions you are also giving other plugins the chance to operate on the filter/action arguments before/after your hook.

If you take a look at class-wp-rest-server.php you can easily look at all available filters and actions related to rest.

You will notice this one in particular:

    /**
     * Filters the array of available endpoints.
     *
     * @since 4.4.0
     *
     * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
     *                         to an array of callbacks for the endpoint. These take the format
     *                         `'/path/regex' => array( $callback, $bitmask )` or
     *                         `'/path/regex' => array( array( $callback, $bitmask ).
     */
    $endpoints = apply_filters( 'rest_endpoints', $this->endpoints );

From my research, this is the very last spot to modify (remove, change or add) endpoints, and is the exact purpose of the filter.

As a sidenote, you don't need to do it "one by one" - you could just do $endpoints = [] to start fresh.

like image 129
Chris Avatar answered Oct 29 '22 02:10

Chris