WordPress函数:wp_remote_retrieve_response_message 仅从原始响应中检索响应消息

江河/ 2023年10月14日/ WordPress/ 浏览 1059

函数原型:


wp_remote_retrieve_response_message( array|WP_Error $response ): string


仅从原始响应中检索响应消息。响应消息。如果给定的参数不正确,则为空字符串。


函数源码:


function wp_remote_retrieve_response_message( $response ) {
	if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
		return '';
	}

	return $response['response']['message'];
}


使用举例:


function wcpdx_get_movie( $title, $id = 0 ) {

	// Collect the args
	$params = array(
		'i' => absint( $id ),
		't' => sanitize_text_field( $title )
	);

	// Generate the URL
	$url = 'http://www.imdbapi.com/';
	$url = add_query_arg( $params, esc_url_raw( $url ) );

	// Make API request
	$response = wp_remote_get( esc_url_raw( $url ) );

	// Check the response code
	$response_code       = wp_remote_retrieve_response_code( $response );
	$response_message = wp_remote_retrieve_response_message( $response );

	if ( 200 != $response_code && ! empty( $response_message ) ) {
		return new WP_Error( $response_code, $response_message );
	} elseif ( 200 != $response_code ) {
		return new WP_Error( $response_code, 'Unknown error occurred' );
	} else {
		return wp_remote_retrieve_body( $response );
        }
}

// Make request
$movie = 'Hairspray';
$response = wcpdx_get_movie( $movie );

// Print error if error, otherwise print information
if ( is_wp_error( $response ) ) {
	echo 'The following error occurred when contacting IMDB: ' . wp_strip_all_tags( $response->get_error_message() );
} else {
	$data = json_decode( $response );
	echo 'The movie ' . esc_html( $data['Title'] ) . ' was released in ' . absint( $data['Year'] ) . '.';
}


发表评论

暂无评论,抢个沙发...

客服 工单