rest_api_init
Fires at the beginning of REST API request processing (when serving the REST request is being prepared).
New REST routes should be registered while this hook fires (see register_rest_route()) to ensure that they are available when a REST request is processed.
Usage
add_action( 'rest_api_init', 'wp_kama_rest_api_init_action' );
/**
* Function for `rest_api_init` action-hook.
*
* @param WP_REST_Server $wp_rest_server Server object.
*
* @return void
*/
function wp_kama_rest_api_init_action( $wp_rest_server ){
// action...
}
- $wp_rest_server(WP_REST_Server)
- The REST server object.
Examples
#1 Create a new endpoint for a plugin
add_action( 'rest_api_init', function(){
register_rest_route( 'myplug/v2', '/posts', array(
'methods' => 'GET',
'callback' => 'myplug_get_post_items',
) );
} );
function myplug_get_post_items(){
$posts = get_posts( array (
'post_status' => 'publish',
'numberposts' => 100
) ) ;
$items = array();
foreach( $posts as $post ){
$items[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'author' => get_the_author_meta( 'display_name', $post->post_author ),
'content' => apply_filters( 'the_content', $post->post_content ),
'teaser' => $post->post_excerpt
);
}
return $items;
}
After installing this code, the endpoint:
GET http://example.com/wp-json/myplug/v2/posts
Will return the site's posts in the specified format.
Changelog
| Since 4.4.0 | Introduced. |
Where the hook is called
rest_api_init
wp-includes/rest-api.php 657
do_action( 'rest_api_init', $wp_rest_server );
Where the hook is used in WordPress
wp-includes/blocks/site-logo.php 103
add_action( 'rest_api_init', 'register_block_core_site_icon_setting', 10 );
wp-includes/blocks/site-logo.php 83
add_action( 'rest_api_init', 'register_block_core_site_logo_setting', 10 );
wp-includes/default-filters.php 546
add_action( 'rest_api_init', 'rest_api_default_filters', 10, 1 );
wp-includes/default-filters.php 547
add_action( 'rest_api_init', 'register_initial_settings', 10 );
wp-includes/default-filters.php 548
add_action( 'rest_api_init', 'create_initial_rest_routes', 99 );
wp-includes/default-filters.php 732
add_action( 'rest_api_init', 'wp_oembed_register_route' );