Stylesheet with cookie works only the second time

1

I have a site that style is defined by the "default" or "cookie" cookie

However, if you enter the first time on it it saves the cookie with the default value, but does not assume the style.

It only works when you reload the page.

On the first line of the header.php page you have:

<?php require('/style/css_cookie_check.php'); ?>

in the stylesheet part:

<link id="style_cor" rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/style/<?php echo $estilo_cor; ?>/style.css" type="text/css" media="screen" />

On the "css_cookie_check.php" page:

<?php
    global $estilo_cor;
    if(!isset($_COOKIE['cor_estilo'])) {
        $estilo_cor = setcookie('cor_estilo', 'padrao', (time() + (2 * 3600)));
    } else {
        $estilo_cor = $_COOKIE['cor_estilo'];
    }
?>
    
asked by anonymous 11.03.2016 / 04:36

1 answer

4

This line of yours has a problem:

$estilo_cor = setcookie('cor_estilo', 'padrao', (time() + (2 * 3600)));

It will not get the cookie value set, only a true or false .

See a solution that assigns value to the variable for the current page and the cookie:

<?php
    global $estilo_cor;
    if( isset( $_COOKIE['cor_estilo'] ) ) {
        $estilo_cor = $_COOKIE['cor_estilo'];
    } else {
        $estilo_cor = 'padrao';
        setcookie( 'cor_estilo', $estilo_cor, ( time() + ( 2 * 3600 ) ) );
    }
?>

If the cookie is set, we use its value. Otherwise, set $estilo_cor and create a cookie with what has been defined.

By the way, it would be cool to set a default for things, you're using $estilo_cor , and 'cor_estilo' . It may even work, but it just creates confusion to keep code like this (PHP is enough, which is all inconsistent).


Taking the global:

In fact, in this case it is even dangerous to do this, because it creates the illusion that you can call the function in other parts of the code, which is not true because it is a cookie but it remains as an example of how to use something from another source without global :

css_cookie_check.php

<?php
    function getStyle() {
       if( isset( $_COOKIE['cor_estilo'] ) ) {
           $estilo_cor = $_COOKIE['cor_estilo'];
       } else {
           $estilo_cor = 'padrao';
           setcookie( 'cor_estilo', $estilo_cor, ( time() + ( 2 * 3600 ) ) );
       }
       return $estilo_cor;
   }
?>

And in main PHP:

<?php
   require('/style/css_cookie_check.php');
   $estilo_cor = getStyle();
?>

In fact, in your case, I would not need my example or even global , but let me illustrate.

    
11.03.2016 / 04:56