Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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'));
    }
});

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

$cookieValue = $_COOKIE['my_cookie'];

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

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

For JavaScript, I'd recommend having a look at one of the jQuery cookie plugins (seeing as jQuery is already part of Wordpress). Try http://plugins.jquery.com/project/Cookie


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...