rest_preload_api_request

函数
rest_preload_api_request ( $memo, $path )
参数
  • (array) $memo Reduce accumulator.
    Required:
  • (string) $path REST API path to preload.
    Required:
返回值
  • (array) Modified reduce accumulator.
定义位置
相关方法
rest_do_requestrest_handle_options_requestrest_ensure_requestrest_parse_request_argwp_preload_resources
引入
5.0.0
弃用
-

rest_preload_api_request: 这是一个WordPress动作,在WordPress REST API处理一个请求之前被触发。这个动作用于在处理请求前预装数据或执行其他设置任务。

将内部请求的结果附加到REST API上,以便预先加载数据,附加到页面上。

预计将在`array_reduce`的背景下调用。

function rest_preload_api_request( $memo, $path ) {
	// array_reduce() doesn't support passing an array in PHP 5.2,
	// so we need to make sure we start with one.
	if ( ! is_array( $memo ) ) {
		$memo = array();
	}

	if ( empty( $path ) ) {
		return $memo;
	}

	$method = 'GET';
	if ( is_array( $path ) && 2 === count( $path ) ) {
		$method = end( $path );
		$path   = reset( $path );

		if ( ! in_array( $method, array( 'GET', 'OPTIONS' ), true ) ) {
			$method = 'GET';
		}
	}

	$path = untrailingslashit( $path );
	if ( empty( $path ) ) {
		$path = '/';
	}

	$path_parts = parse_url( $path );
	if ( false === $path_parts ) {
		return $memo;
	}

	$request = new WP_REST_Request( $method, $path_parts['path'] );
	if ( ! empty( $path_parts['query'] ) ) {
		parse_str( $path_parts['query'], $query_params );
		$request->set_query_params( $query_params );
	}

	$response = rest_do_request( $request );
	if ( 200 === $response->status ) {
		$server = rest_get_server();
		/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
		$response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $server, $request );
		$embed    = $request->has_param( '_embed' ) ? rest_parse_embed_param( $request['_embed'] ) : false;
		$data     = (array) $server->response_to_data( $response, $embed );

		if ( 'OPTIONS' === $method ) {
			$memo[ $method ][ $path ] = array(
				'body'    => $data,
				'headers' => $response->headers,
			);
		} else {
			$memo[ $path ] = array(
				'body'    => $data,
				'headers' => $response->headers,
			);
		}
	}

	return $memo;
}

常见问题

FAQs
查看更多 >