需要正确的方法来在WordPress中设置cookie [英] need the right way to setcookie in wordpress

查看:51
本文介绍了需要正确的方法来在WordPress中设置cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整天都在寻找如何在wordpress中设置cookie的方法.以我的方式,我发现(使用开发人员工具栏)已设置cookie,但仍无法正常工作.我有2个文件,第一个包含登录表单,重定向到另一个页面以设置cookie,然后返回另一个页面以检查它是否正常工作.经过测试的域是这样的:blog.mydomain.com.这是setcookie文件:

i've been looking the whole day how to setcookies in wordpress. in my way i found out (using the developer toolbar) that the cookie is set but still not working. i have 2 files the first contains the login form redirecting to another page to set the cookie and return to another page to check if it's working. domain which is tested on is like this : blog.mydomain.com. here's the setcookie file :

<?php
setcookie("user_name","test",time()+3600);
?>

并像这样检查cookie:

and chcking the cookie like this :

if(isset($_COOKIE["user_name"])){
echo "cookie exists";
}
else{
echo "cookie doesn't exist";
}

我已经阅读了许多有关此问题的主题,但没有明确的答案.预先感谢

i've read many topics about this issue but there was no clear answer. Thanks in advance

推荐答案

当您在将输出发送到浏览器后尝试设置cookie时,通常会发生这种情况.要在WP中设置cookie,您应该使用"init"钩子在init上设置cookie.

This typically happens when you try to set a cookie after sending output to the browser. To set a cookie in WP, you should use the 'init' hook to set the cookie on init.

function set_username_cookie() {
    if (!isset($_COOKIE['user_name'])) {
        setcookie("user_name","test",time()+3600);
    }
}
add_action( 'init', 'set_username_cookie');

这篇关于需要正确的方法来在WordPress中设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆