rest_api_init
Это хук WordPress - rest_api_init. Плагин его просто использует.
Срабатывает в начале обработки 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 сервера.
Примеры
#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
Будет отдавать посты сайта в указанном формате.
Где вызывается хук
rest_api_init
woocommerce/includes/cli/class-wc-cli-runner.php 59
do_action( 'rest_api_init', $wp_rest_server );
Где используется хук в WooCommerce
woocommerce/includes/class-wc-api.php 29
add_action( 'rest_api_init', array( $this, 'register_wp_admin_settings' ) );
woocommerce/includes/rest-api/Server.php 31
add_action( 'rest_api_init', array( $this, 'register_rest_routes' ), 10 );
woocommerce/packages/woocommerce-blocks/src/Shipping/ShippingController.php 53
add_action( 'rest_api_init', [ $this, 'register_settings' ] );
woocommerce/src/Admin/API/Init.php 46
add_action( 'rest_api_init', array( $this, 'rest_api_init' ) );
woocommerce/src/Internal/Admin/WCAdminUser.php 21
add_action( 'rest_api_init', array( $this, 'register_user_data' ) );