do_action( ‘rest_api_init’, WP_REST_Server $wp_rest_server )

Fires when preparing to serve a REST API request.

Description

Endpoint objects should be created and register their hooks on this action rather than another action to ensure they’re only loaded when needed.

Parameters

$wp_rest_serverWP_REST_Server
Server object.

Source

do_action( 'rest_api_init', $wp_rest_server );

Changelog

VersionDescription
4.4.0Introduced.

User Contributed Notes

  1. Skip to note 3 content

    /**
    * Example: Register a custom REST route using rest_api_init.
    *
    * The callback receives the WP_REST_Server instance as its single parameter.
    *
    * @param WP_REST_Server $wp_rest_server The REST API server.
    */
    function sample_register_rest_routes( WP_REST_Server $wp_rest_server ) {
    register_rest_route(
    ‘sample/v1’,
    ‘/hello’,
    array(
    ‘methods’ => WP_REST_Server::READABLE,
    ‘callback’ => ‘sample_rest_hello_callback’,
    ‘permission_callback’ => ‘__return_true’,
    )
    );
    }
    add_action( ‘rest_api_init’, ‘sample_register_rest_routes’, 10, 1 );

    /**
    * Callback for the /sample/v1/hello route.
    *
    * @return array
    */
    function sample_rest_hello_callback() {
    return array(
    ‘message’ => ‘Hello from the REST API!’,
    ‘time’ => current_time( ‘mysql’ ),
    );
    }

  2. Skip to note 4 content


    /**
    * Register a custom REST API route using the rest_api_init action.
    *
    * The callback receives the WP_REST_Server instance.
    *
    * @param WP_REST_Server $wp_rest_server The REST API server instance.
    */
    function sample_register_rest_routes( WP_REST_Server $wp_rest_server ) {

    register_rest_route(
    'sample/v1',
    '/hello',
    array(
    'methods' => WP_REST_Server::READABLE,
    'callback' => 'sample_rest_hello_callback',
    'permission_callback' => '__return_true',
    )
    );
    }
    add_action( 'rest_api_init', 'sample_register_rest_routes', 10, 1 );

    /**
    * Callback for the /wp-json/sample/v1/hello endpoint.
    *
    * @return array
    */
    function sample_rest_hello_callback() {
    return array(
    'message' => 'Hello from the REST API!',
    'time' => current_time( 'mysql' ),
    );
    }

You must log in before being able to contribute a note or feedback.