0

I am trying to create some functionality in a WordPress site that will create a cookie when a user visits a location page that stores the city of the location page they have visited. However I am getting an error from WordPress that I cannot modify header information. I included the below function in my functions.php file:

function set_city_cookie($city) { 

    if(!isset($_COOKIE['city_cookie'])) {

    // set a cookie 
    setcookie('city_cookie', $city, time()+30);
     $last_city=$_COOKIE['city_cookie'];
        return $last_city;
    }

    } 
    add_action('init', 'set_city_cookie');

I then called the function in my single-locations.php like this:

set_city_cookie($city); 

Does anyone have any ideas as to why this wouldn't work?

Blaise
  • 137
  • 11

1 Answers1

1

Cookies are sent in the HTTP response header. Since the HTML content already started, you cannot go back to the header and add the cookie. That's why you're having an error like : How to fix “Headers already sent” error in PHP

From http://php.net/setcookie:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.

You should call your set_city_cookie($city); before any HTML output :

<?php

set_city_cookie($city); 
...

?>
<!DOCTYPE html>
André DS
  • 1,823
  • 1
  • 14
  • 24
  • This makes sense, when I called the functions in areas above the `html` I no longer got any errors. However my function does still not seem to be actually setting any cookies. When I set to a variable, `var_dump` etc I just get `NULL` – Blaise Nov 07 '18 at 21:19
  • Did you try to `print_r($_COOKIE);`? – André DS Nov 07 '18 at 21:22
  • I just tried that and am just getting an array like this with a bunch of numbers/letters where the dots are: `[has_js] => 1 [wordpress_logged_in_.....] =>....[wp-settings-1] =>....[wp-settings-time-1] =>....` I am guessing it is just WP cookie. I don't see my `city_cookie` in there – Blaise Nov 07 '18 at 21:42
  • 1
    $_COOKIE is set when the page loads, due to the stateless nature of the web. It'll be accessible on a page reload. If you want immediate access, you will have to use your $city variable. – André DS Nov 07 '18 at 22:11