如何在 WordPress 中设置、获取和销毁 cookie? [英] How can I set, get and destroy cookies in WordPress?

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

问题描述

如何在 WordPress 中设置、获取和销毁 cookie?

How can I set, get and destroy cookies in WordPress?

我浏览了网页,但我无法获得清晰的想法,请帮助我找到方法.

I surfed the web but I can't get clear ideas, please help me find how.

推荐答案

您可以在服务器端使用 PHP 或客户端使用 JavaScript 检索和操作 cookie.

You can either retrieve and manipulate cookies on the server side using PHP or client side, using JavaScript.

在 PHP 中,您可以使用 setcookie() 设置 cookie.请注意,这必须在任何输出发送到浏览器之前完成,这在 Wordpress 中可能是一个很大的挑战.您几乎只能使用一些早期运行的钩子,您可以通过插件或主题文件(例如functions.php)设置这些钩子,例如

In PHP, you set cookies using setcookie(). Note that this must be done before any output is sent to the browser which can be quite the challenge in Wordpress. You're pretty much limited to some of the early running hooks which you can set via a plugin or theme file (functions.php for example), eg

add_action('init', function() {
    if (!isset($_COOKIE['my_cookie'])) {
        setcookie('my_cookie', 'some default value', strtotime('+1 day'));
    }
});

在 PHP 中检索 cookie 要容易得多.只需从 $_COOKIE 超级全局中按名称获取它们,例如

Retrieving cookies in PHP is much easier. Simply get them by name from the $_COOKIE super global, eg

$cookieValue = $_COOKIE['my_cookie'];

取消设置 cookie 需要设置一个过去的过期日期,例如

Unsetting a cookie requires setting one with an expiration date in the past, something like

setcookie('my_cookie', null, strtotime('-1 day'));

<小时>

对于 JavaScript,我建议您查看其中一个 jQuery cookie 插件(因为 jQuery 已经是 Wordpress 的一部分).试试 http://plugins.jquery.com/project/Cookie

这篇关于如何在 WordPress 中设置、获取和销毁 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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