函数文档

wp_remote_retrieve_cookie()

💡 云策文档标注

概述

wp_remote_retrieve_cookie() 函数用于从 HTTP 响应中按名称检索单个 cookie。它返回 WP_Http_Cookie 对象,如果未找到则返回空字符串。

关键要点

  • 参数:$response(数组或 WP_Error,必需)为 HTTP 响应;$name(字符串,必需)为要检索的 cookie 名称。
  • 返回值:WP_Http_Cookie 对象或空字符串(如果 cookie 不存在)。
  • 内部实现:通过 wp_remote_retrieve_cookies() 获取所有 cookies,然后遍历匹配指定名称。
  • 相关函数:wp_remote_retrieve_cookies() 用于检索所有 cookies;wp_remote_retrieve_cookie_value() 用于检索 cookie 值。
  • 版本历史:自 WordPress 4.4.0 引入。

代码示例

$json = wp_remote_get( 'http://localhost/wp-rest-api/wp-json/wp/v2/posts/' );
$sess_cookie = wp_remote_retrieve_cookie($json, 'PHPSESSID');

echo '';
print_r($sess_cookie);
echo '';

📄 原文内容

Retrieves a single cookie by name from the raw response.

Parameters

$responsearray|WP_Errorrequired
HTTP response.
$namestringrequired
The name of the cookie to retrieve.

Return

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

Source

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 '';
}

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes