如何在 Wordpress 中设置 cookie [英] How to set a cookie in Wordpress
问题描述
我正在尝试在 wordpress 中设置 cookie.我的 cookie 设置如下:
I'm trying to set a cookie in wordpress. I have my cookie set like this :
<?php setcookie('test', 'test', 0, '/', '/'); ?>
在我的主题的 header.php 中,但是当我转到浏览器查看我的网站时出现此错误
in header.php of my theme, but when I go to my browser to view my website I get this error
Warning: Cannot modify header information - headers already sent by (output started at /home/content/19/9468119/html/wp-content/themes/twentyeleven/header.php:27) in /home/content/19/9468119/html/wp-content/themes/twentyeleven/header.php on line 201
而且我的 cookie 也没有设置.如何在 wordpress 中设置 cookie?
and also my cookie doesnt set. How do I set a cookie in wordpress?
我也试过这个
function set_new_cookie() {
setcookie('test', 'test', 0, '/', '/');
}
add_action( 'init', 'set_new_cookie');
推荐答案
你必须在输出任何东西之前设置它们
You have to set them before anything is outputted
看那里:如何设置,获取并销毁 Wordpress 中的 cookie?
如果您在 function.php 中使用主题
If you are using a theme in function.php
function set_new_cookie() {
//setting your cookies there
}
add_action( 'init', 'set_new_cookie');
您的到期日期日期为 0,因此您的 cookie 将立即被删除,请查看 php 文档:
Your expiration date is 0 so you cookies will be deleted right away look at the php doc:
来自 php.net:
From php.net:
如果设置为 0 或省略,cookie 将在结束时过期会话(当浏览器关闭时).
If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
http://php.net/manual/en/function.setcookie.php
你必须像这样设置它,例如:
You have to set it like this for example :
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
这篇关于如何在 Wordpress 中设置 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!