简体   繁体   English

如何在Wordpress中设置cookie

[英]How to set a cookie in Wordpress

I'm trying to set a cookie in wordpress. 我正在尝试在wordpress中设置一个cookie。 I have my cookie set like this : 我的cookie设置如下:

<?php setcookie('test', 'test', 0, '/', '/');  ?>

in header.php of my theme, but when I go to my browser to view my website I get this error 在我的主题的header.php中,但当我访问我的浏览器查看我的网站时,我收到此错误

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

and also my cookie doesnt set. 而且我的cookie没有设置。 How do I set a cookie in wordpress? 如何在wordpress中设置cookie?

I have also tried this 我也尝试过这个

 function set_new_cookie() {
    setcookie('test', 'test', 0, '/', '/');
}
add_action( 'init', 'set_new_cookie');

You have to set them before anything is outputted 你必须在输出任何东西之前设置它们

look there: How can I set, get and destroy cookies in Wordpress? 看那里: 如何在Wordpress中设置,获取和销毁cookie?

If you are using a theme in function.php 如果您在function.php中使用主题

function set_new_cookie() {
    //setting your cookies there
}
add_action( 'init', 'set_new_cookie');

Your expiration date is 0 so you cookies will be deleted right away look at the php doc: 您的到期日期为0,因此您将立即删除cookie以查看php doc:

EDIT: From php.net: 编辑:来自php.net:

If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes). 如果设置为0或省略,则cookie将在会话结束时(浏览器关闭时)到期。

http://php.net/manual/en/function.setcookie.php 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 */
  1. Setting a Cookie: The below example will set the cookie that expired for one hour (60*60 seconds) since it set with COOKIEPATH and COOKIE_DOMAIN was defined by WordPress according to your site path and domain. 设置Cookie:以下示例将设置已过期一小时(60 * 60秒)的Cookie,因为它使用COOKIEPATH设置,而COOKIE_DOMAIN是由WordPress根据您的站点路径和域定义的。

     setcookie( 'my-cookie-name', 'my-cookie-value', time() + 3600, COOKIEPATH, COOKIE_DOMAIN ); 
  2. Getting a Cookie: Getting a cookie can be done by using variable $_COOKIE which contains an associative array. 获取Cookie:使用包含关联数组的变量$ _COOKIE可以获取cookie。

     $myCookie = isset( $_COOKIE['my-cookie-name'] ) ? $_COOKIE['my-cookie-name'] : 'Not Set!!'; 
  3. Delete or Unset a Cookie: It is same as the above instruction #1, just with a negative time to expire the cookie; 删除或取消设置Cookie:与上述指令#1相同,只是否定时间使Cookie失效;

     setcookie( 'my-cookie-name', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM