在将任何内容写入页面之前(在发送标题之前),您需要删除cookie。
要设置cookie,请包括路径、域,我还建议将最后2个参数设置为true($secure
和$httponly
). 您还需要将相同的参数提供给setcookie()
删除时,除了$expiry
(应该是负数)和$value
(应为空“”)。
如果要通过cookie传递json,似乎需要base64_encode
它也是,否则它将无法正确解码。
所有这些都应该在一个类中完成,这样您以后就可以在代码中访问cookie的值。该类可以添加到插件或函数中。php。
下面是一个示例,我们使用cookie存储操作响应,然后在重定向后将其显示给用户:
class my_custom_class {
const MY_COOKIE_NAME_JSON = \'my_cookie_name_json\';
const COOKIE_LIFETIME = 3600;
private $cookie_value;
function __construct() {
// ensure you are deleting cookie before headers are sent
add_action(\'init\', [$this, \'process_cookie_json\'], 10);
// uses bootstrap alert to format return message
add_filter(\'the_content\', [$this, \'filter_the_content_in_the_main_loop\'], 1);
}
static function some_action_that_sets_the_cookie($message, $response_type = \'success\') {
$responses = [];
if (isset($_COOKIE[self::MY_COOKIE_NAME_JSON]))
$responses = json_decode(base64_decode($_COOKIE[self::MY_COOKIE_NAME_JSON]));
$responses[$response_type][] = $message;
self::set_cookie_json($responses);
}
static function set_cookie_json(array $cookie_value) {
setcookie(self::MY_COOKIE_NAME_JSON, base64_encode(json_encode($cookie_value)), time() + self::COOKIE_LIFETIME, "/", $_SERVER[\'HTTP_HOST\'], true, true);
}
function process_cookie_json() {
if (!isset($_COOKIE[self::MY_COOKIE_NAME_JSON]))
return false;
$this->cookie_value = json_decode(base64_decode($_COOKIE[self::MY_COOKIE_NAME_JSON]), true);
setcookie(self::MY_COOKIE_NAME_JSON, \'\', -1, "/", $_SERVER[\'HTTP_HOST\'], true, true);
unset($_COOKIE[self::MY_COOKIE_NAME_JSON]);
}
function filter_the_content_in_the_main_loop($content) {
if (!$this->cookie_value || !is_array($this->cookie_value))
return $content;
$alerts = [];
foreach ($this->cookie_value as $response_type => $messages)
$alerts[] = \'<div class="alert alert-\' . $response_type . \'" role="alert">\' . implode(PHP_EOL, $messages) . \'</div>\';
return implode(null, $alerts) . $content;
}
}
$my_custom_class = my_custom_class;
然后,您可以通过以下方式设置cookie:
my_custom_class::some_action_that_sets_the_cookie(\'the message\');