jmccole83
2/27/2019 - 2:42 PM

WP - Test and set cookie, update with JS

Use an if statement to check a cookie is not set, if not set, set the cookie with a value of 'null'.

Use JS to change the cookie value on click, or by selecting an option.

/*
 * Set cookie
 */
add_action( 'init', function() {
  
  if ( !isset($_COOKIE['cookie_name']) ) {
  setcookie( 'cookie_name', 'null', strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, 1 );
  }

} );
// Set cookie value on click
$('.option').click(function(){
  var value = $(this).attr('id');
  document.cookie = 'cookie_name=' + value + ';max-age=2592000;path=/';
  location.reload(true); // 'true' hard refreshes
});

// swap cookie value from select option
$('#view-switch').change(function(){
  var value = $(this).val();
  document.cookie = 'cookie_name=' + value + ';max-age=2592000;path=/';
  location.reload(true); // 'true' hard refreshes
});