wp_remote_retrieve_cookie()
Retrieves the data of a specific named cookie from the response passed to the request.
Used By: wp_remote_retrieve_cookie_value()
No Hooks.
Returns
WP_Http_Cookie|String.
- WP_Http_Cookie object.
An empty stringif the specified cookie is not present in the response to the request.
Usage
wp_remote_retrieve_cookie( $response, $name );
- $response(array) (required)
- Response to the request obtained by one of the functions: wp_remote_*()
- $name(string) (required)
- The name of the cookie whose data (object) should be retrieved.
Examples
#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() wp remote retrieve cookie code WP 6.9
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 '';
}