Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 869
Ravichandran Jothi Avatar asked May 31 '11 04:05

Ravichandran Jothi


People also ask

How do I get rid of cookies on WordPress?

Deleting Cookies in WordPress If you ever want to delete a cookie in WordPress, simply use the unset() function. Copy and paste the code snippet below. unset ( $_COOKIE [ 'fx_visit_time' ]);

How do I change cookie settings in WordPress?

Go to Settings and then click Show advanced settings… In the “Privacy” section click on Content Settings. A modal will display giving you options for how you want to store cookies on your site. Leave as is and go to All cookies and site data.

Where is cookie settings in WordPress?

Type “Content Settings” into the text box at the top of the screen. Click on the Content Settings option. The first option you should see is Cookies. Click on the Cookies option and select the See all cookies and site data option.


2 Answers

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

like image 100
Phil Avatar answered Sep 18 '22 15:09

Phil


Try this code inside function.php to play with Cookies in WordPress

Set a Cookie in WordPress

add_action( 'init', 'my_setcookie' ); function my_setcookie() { setcookie( 'my-name', 'my-value', time() + 3600, COOKIEPATH, COOKIE_DOMAIN   ); } 

Get a Cookie in WordPress

add_action( 'wp_head', 'my_getcookie' ); function my_getcookie() { $alert = isset( $_COOKIE['my-name'] ) ? $_COOKIE['my-name'] : 'not set';  echo "<script type='text/javascript'>alert('$alert')</script>"; } 

Delete or Unset a Cookie in WordPress

add_action( 'init', 'my_deletecookie' ); function my_deletecookie() { setcookie( 'my-name', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN ); } 
like image 26
Smruti Ranjan Avatar answered Sep 18 '22 15:09

Smruti Ranjan