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?

2 s
2

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, "https://wordpress.stackexchange.com/", COOKIE_DOMAIN );
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *