wp_remote_retrieve_cookie()WP 4.4.0

Retrieve a single cookie by name from the raw response.

No Hooks.

Return

WP_Http_Cookie|String. The WP_Http_Cookie object, or empty string if the cookie is not present in the response.

Usage

wp_remote_retrieve_cookie( $response, $name );
$response(array|WP_Error) (required)
HTTP response.
$name(string) (required)
The name of the cookie to retrieve.

Examples

0

#1 Get the data of a separate cookie

Suppose we sent a request and received two cookies in response: mycookie and mycook. Now we need to get the data of one cookie mycookie. By data we do not mean the value of the cookie, but all cookie data, which are represented as an object WP_Http_Cookie

To demonstrate such a request, let's use the service httpbin.org, which allows you to set cookies in the response received from the server.

$url = 'https://httpbin.org/cookies/set?mycookie=value1&mycook=value2';

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

$mycookie = wp_remote_retrieve_cookie( $response, 'mycookie');

print_r( mycookie );

/*
WP_Http_Cookie Object
(
	[name] => mycookie
	[value] => value1
	[expires] => 
	[path] => /
	[domain] => httpbin.org
)
*/

Changelog

Since 4.4.0 Introduced.

wp_remote_retrieve_cookie() code WP 6.5.3

function wp_remote_retrieve_cookie( $response, $name ) {
	$cookies = wp_remote_retrieve_cookies( $response );

	if ( empty( $cookies ) ) {
		return '';
	}

	foreach ( $cookies as $cookie ) {
		if ( $cookie->name === $name ) {
			return $cookie;
		}
	}

	return '';
}