Home > other >  wordpress: cookie data not being set until after first browser refresh
wordpress: cookie data not being set until after first browser refresh

Time:11-04

I have a modal with a form in it in which people can use to add their address and then submit it. The value of the form is being saved via the GET method. I'm using the value from that input to set a cookie called origin (also the name of the input) in my function.php file:

function action_init() {
    $path = parse_url( get_option('siteurl'), PHP_URL_PATH );
    $host = parse_url( get_option('siteurl'), PHP_URL_HOST );
    $expiry = time()   36000;
    $origin = isset($_GET['origin']) ? $_GET['origin'] : null;

    if( ( $origin != null ) ) {
        setcookie( 'origin', $origin, $expiry, $path, $host );
    }
}
add_action( 'init', 'action_init' );

After form submission the browser redirects to a page that queries results based on the user's address. That's all working fine.

My problem is that on that same search result page I'm trying to display the user's address like so:

if(isset($_COOKIE['origin'])) {
    echo $_COOKIE['origin'];
};

The first time the search result page loads, that cookie is not being called to the page. It's only if I refresh the browser that it finally shows up.

Is there a way I can get that cookie to be displayed right from the first page load?

CodePudding user response:

After form submission the browser redirects to a page that queries results

Sounds like that was not an actual redirect (second request), but rather where you submitted your form data to in the first place. In that case, of course the cookie is not available yet - because it will only be created in the processing of that request.

But then you would have the value available via $_GET to begin with, so take it from there in that instance then.

  • Related