Alex
Alex

Reputation: 81

Random color in cookie with wordpress

I randomly choose a dominant color when the visitor arrive on the website, then I want to store this color in a cookie during 1 hour.

And I'm working on wordpress. For the moment I've got this on my function.php

add_action( 'init', 'setting_my_first_cookie' );
function setting_my_first_cookie() {
    $colourRange = array('#965c5d', '#5f797a', '#bc8b6a', '#7fc3a2', '#89383a', '#f28c5d');
    $colourTheOnlyOne = $colourRange[array_rand($colourRange, 1)];
    $cookieColor = 'cookieColor';
    $cookieValue = $colourTheOnlyOne; 
    setcookie( $cookieColor, $cookieValue, 60 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
}

The problem is every time I refresh the page a new color is set… don't understand why !

Upvotes: 1

Views: 54

Answers (2)

Alex
Alex

Reputation: 81

So I finally solve my problem with that and after in the template I check if a cookie is available, if not I display the

$colorRange = array('#965c5d', '#5f797a', '#bc8b6a', '#7fc3a2', '#89383a', '#f28c5d');
$cookieValue = $colorRange[array_rand($colorRange, 1)];
global $cookieValue;

add_action( 'init', 'setting_cookie' );
function setting_cookie() { 
    global $cookieValue;
    $cookieTheValue = $cookieValue;
    $cookieColor = 'cookieColor';
    if (!isset($_COOKIE[$cookieColor])) {
        setcookie( $cookieColor, $cookieTheValue, time()+60, COOKIEPATH, COOKIE_DOMAIN );
    }
}

Upvotes: 0

James Paterson
James Paterson

Reputation: 2915

You need to check the cookie value to see if it there to avoid resetting it. You are essentially overwriting your cookie every time you reload the page.

add_action( 'init', 'setting_my_first_cookie' );
function setting_my_first_cookie() {
    $cookieColor = 'cookieColor';
    if (!isset($_COOKIE[$cookieColor])) {
        $colourRange = array('#965c5d', '#5f797a', '#bc8b6a', '#7fc3a2', '#89383a', '#f28c5d');
        $cookieValue = $colourRange[array_rand($colourRange, 1)];
        setcookie( $cookieColor, $cookieValue, 60 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
    }
}

This checks for the cookie 'cookieColor' and if it is found, does not write the cookie.

Upvotes: 1

Related Questions