0

I have created a landing page that is only available to a certain audience. When users visit this page I would like to create a cookie that can be passed on upon completing a booking form on another page. I am using Wordpress and can't figure out how to set a page specific cookie. I am able to set a global cookie through the functions.php. Right now I have tried out a function using the is_page argument to check whether the specific page is being viewed:

    add_action( 'init', 'setting_my_first_cookie' );
    function setting_my_first_cookie() {

    if (is_page('name-of-page')) { 

    $cookie_name = "user";
    $cookie_value = "John Doe";
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    }
    }

Any ideas where I am going wrong? Or maybe using a cookie is a totally incorrect approach. In that case I would appreciate a hint, how I could handle such a problem. Many thanks for your help!

1

WordPress doesn't know if it's a page yet, init fires before the query is run. You need to hook a later action, like wp. Have a look at Action Reference to see the order of actions during a request.

0

You can always use Session intead of cookie and run it with jQuery, set it in a function:

$(function() {
 // set landingPage to 1 to set the session to "True"
 // or check for not landingPage (!sessionStorage.landingPage)
 // to do something if it's not set
 sessionStorage.landingPage = 1;
}); 

And then you can see if the user has that session and act on that on all other pages (for vice a versa switch the else actions around):

$(function() {
    // if landingPage session is not set:
    if (sessionStorage.landingPage) {
        // do something here if landingPage is set to 1
    } else {
        // do nothing, or set landingPage to 1 for next time
    }
});
  • Thank you Nathaniel for this solution. The problem with the session is that it will expire once the browser is closed, wouldn't it? It'd be great to use a cookie instead as I want to make sure the 'tag' is passed through even when they complete the form at a later date. – user3645783 May 9 '17 at 16:29
  • The session lasts as long as it remains in that users browser and isn't cleared from cache. Any other solution, if it's to persist, will most likely need to be attached to that users account in the database so session is the quickest and easiest way to do this I reckon. You have the same issue with cookies. – Nathaniel Flick May 9 '17 at 17:17

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.