3

I need to set a cookie based on a GET variable so my customers can get a coupon code on our site even if they move around after selecting the coupon link.

I am using the code here: Gravity Help to populate the coupon field based on the cookie. Just the second half of the code.

I need to set the coupon code in a cookie. There is a piece here: Setting a Cookie using a variable from the URL But I think that will also set an empty cookie if there is no variable which I think would over write the code if they user browses around the site. What would be the best way to make sure that function only runs if the variable is set?

3

Just check if the variable is set, using the code from your link:

add_action( 'init', 'set_agent_cookie' );

function set_agent_cookie() {
    if (isset($_GET['code'])) {
      $name = 'agent';
      $id = $_GET['code'];    
       setcookie( $name, $id, time() + 3600, "/", COOKIE_DOMAIN );
    }
}
  • I should have known it was that easy. I was expecting there to be some special wordpress function. Thanks! It works like a charm! – JpaytonWPD Feb 19 '17 at 15:37
1

Yes you just need to wrap in an isset check before setting the cookie:

$name = 'cookiename';
$expires = time() + 3600;
if (isset($_GET['code'])) {
    $value = $_GET['code'];
    setcookie($name, $value, $expires, '/', COOKIE_DOMAIN);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.