rest_api_initхук-событиеWP 4.4.0

Срабатывает в начале обработки REST API запроса (когда подготавливается обслуживание REST запроса).

Во время срабатывания этого хука нужно регистрировать новые маршруты REST (см. register_rest_route()), чтобы быть уверенным, что они будут срабатывать в момент REST запроса.

Использование

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)
Объект REST сервера.

Примеры

3

#1 Создание новой конечной точки для своего плагина

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;
}

После установки этого кода, эндпоинт:

GET http://example.com/wp-json/myplug/v2/posts

Будет отдавать посты сайта в указанном формате.

Список изменений

С версии 4.4.0 Введена.

Где вызывается хук

rest_get_server()
rest_api_init
wp-includes/rest-api.php 597
do_action( 'rest_api_init', $wp_rest_server );

Где используется хук в WordPress

wp-includes/blocks/site-logo.php 78
add_action( 'rest_api_init', 'register_block_core_site_logo_setting', 10 );
wp-includes/blocks/site-logo.php 95
add_action( 'rest_api_init', 'register_block_core_site_icon_setting', 10 );
wp-includes/default-filters.php 511
add_action( 'rest_api_init', 'rest_api_default_filters', 10, 1 );
wp-includes/default-filters.php 512
add_action( 'rest_api_init', 'register_initial_settings', 10 );
wp-includes/default-filters.php 513
add_action( 'rest_api_init', 'create_initial_rest_routes', 99 );
wp-includes/default-filters.php 674
add_action( 'rest_api_init', 'wp_oembed_register_route' );