Reputation: 360
I have been trying to set a cookie which will change the stylesheet of the theme based on a button click. I can't figure out why it isn't working, please could someone explain where I am going wrong?
These are my buttons (header.php):
<a href="?style=as1" >AS1</a>
<a href="?style=as2" >AS2</a>
<a href="?style=as3" >AS3</a>
This is my stylesheet (header.php):
<link rel="stylesheet" type="text/css" media="all" id="accessible-stylesheet" href="<?php echo get_template_directory_uri(); ?>/<?php echo $stylesheet; ?>" />
This is my function (functions.php):
// Accessible Stylesheet Cookie
$stylesheet = "as1";
if ( isset($_GET['style']) ) {
if ($_GET['style'] == "as2") {
$stylesheet = "as2";
} else if ($_GET['style'] == "as3") {
$stylesheet = "as3";
}
setcookie("style","$stylesheet","3600*7");
}
$as1stylesheet = 'css/colors-as1.css';
$as2stylesheet = 'css/colors-as2.css';
$as3stylesheet = 'css/colors-as3.css';
$stylesheet = $as1stylesheet;
if ( isset($_COOKIE['stylesheet'] ) ) {
if ( $_COOKIE['stylesheet'] == "as2" ) {
$stylesheet = $as2stylesheet;
} else if ( $_COOKIE['stylesheet'] == "as3" ) {
$stylesheet = $as3stylesheet;
}
}
I am getting no errors, I can't figure out where I am going wrong. The stylesheet isn't being set at all.
Upvotes: 1
Views: 111
Reputation: 5639
You have a few errors in your PHP code, and are using the variables incorrectly. This seems more concise.
You can't set and call the superglobal $_COOKIE on the same page. Here's an excerpt from the manual... https://www.php.net/manual/en/function.setcookie.php
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array.
$stylesheet = "as1";
// Check for cookie and set one if it's not set
if (!isset($_COOKIE['style'])) setcookie('style', $stylesheet, time() + (3600*7));
// If there is a cookie, the stylesheet is from the cookie
if ( isset($_COOKIE['style'] ) ) {
$stylesheet = $_COOKIE['style'];
}
// If there's a get parameter set the cookie to it (for next page load), and set the stylesheet for this page load
if ( isset($_GET['style']) ) {
$stylesheet = $_GET['style'];
setcookie('style', $stylesheet, time() + (3600*7));
}
<link rel="stylesheet" type="text/css" media="all" id="accessible-stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/colors-<?php echo $stylesheet; ?>.css" />
Upvotes: 1
Reputation: 318
Your cookie name is style and you are trying to retrieve the cookie stylesheet
setcookie("style","$stylesheet","3600*7");
and you don't need to put the value in quotes if you are only going to put a variable in it:
setcookie("stylesheet",$stylesheet,"3600*7");
Upvotes: 0