wp_remote_retrieve_response_message()WP 2.7.0

Retrieve only the response message from the raw response.

Will return an empty string if incorrect parameter value is given.

No Hooks.

Return

String. The response message. Empty string if incorrect parameter given.

Usage

wp_remote_retrieve_response_message( $response );
$response(array|WP_Error) (required)
HTTP response.

Examples

0

#1 Demo

$res = wp_remote_get('http://wp-kama.com');
echo wp_remote_retrieve_response_message( $res ); //> OK

$res = wp_remote_get('http://wp-kama.com/error404');
echo wp_remote_retrieve_response_message( $res ); //> Not Found
0

#2 Get information about the film from Kinopoisk

This example shows how to retrieve movie information from the Kinopoisk site and check the request for errors:

/**
 * Get information about the movie from Kinopoisk
 * Powered by http://docs.kinopoiskapi.apiary.io/.
 *
 * @param int $id ID of the movie on the site
 * @return string|WP_Error Gets response body if successful and WP_Error object if unsuccessful
 */
function kinopoisk_get_movie( $id ) {

	// Parameters of GET request
	$params = array(
		'filmID' => absint( $id ),
	);

	// Create a URL with parameters
	$url = 'http://api.kinopoisk.cf/getFilm';
	$url = add_query_arg( $params, esc_url_raw($url) );

	//request
	$response = wp_remote_get( $url );

	// Check answer code
	$response_code    = wp_remote_retrieve_response_code( $response );
	$response_message = wp_remote_retrieve_response_message( $response );
	$response_body    = json_decode(wp_remote_retrieve_body( $response ));

	if ( 200 != $response_code && ! empty( $response_message ) ) {
		return new WP_Error( $response_code, $response_message );
	}
	if ( 200 != $response_code ) {
		return new WP_Error( $response_code, 'Unknown error' );
	}
	if( ! $response_body ) {
		return new WP_Error( 'nodata', 'No data on the movie or no such movie in the database' );
	}    

	return $response_body;

}

// Query
$res = kinopoisk_get_movie( 714888 );

// Output an error or information
if ( is_wp_error( $res ) ) {
	echo 'IMDB query error: '. wp_strip_all_tags( $res->get_error_message() );
}
else {
	echo 'Movie: "' . esc_html( $res->nameRU ) .' ('. (int) $res->year .'.) Rating: '. $res->ratingData->rating;
}

// as a result we get:
// Movie: "Star Wars: The Force Awakens" (2015). Rating: 7.3

Changelog

Since 2.7.0 Introduced.

wp_remote_retrieve_response_message() code WP 6.7.1

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

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