Theme Switcher With PHP Variables In CSS

Theme Switcher With PHP Variables In CSS

January 20th, 2010

There are many theme switchers out there that do the job just great. Whether you change the theme via a server sided script like PHP or through Javascript most theme switchers do the job of changing the CSS file that styles your content.  But what if you want to just change a few of the styles on the page? What if you only want to have to update just one CSS file?

Requirements

  • A basic knowledge of PHP
  • Basic knowledge of HTML & CSS

Fortunately there is a way that you can use a server sided scripting language like PHP store CSS variables in a PHP file and have the server send back the results to the browser with the mime type text/css. As explained by Chris Coyier over at CSS-Tricks you can use PHP to create a CSS file. We’re going to take this a step further and create a theme switcher using the techniques used by Chris.

First of all we want to create a PHP file for the content of our page.  We will keep this pretty simple for the example but there is no reason why you couldn’t implement this into a site with far content and complex styles. Here is a simple starter page structure. Notice that the link to the CSS file is actually a PHP file located within a folder named css.


<! DOCTYPE HTML >
< html >
<head>
<title>PHP Variables In CSS Demo</title>
< meta http -equiv="Content -Type" content="text /html; charset = utf-8" />
<link rel="stylesheet" href="css/style.php" type="text/css" media="screen" />
</head>
<body>
<div id="wrap">
<div id="nav">
<img src="images/adamoliver.jpg" alt="adamoliver.net" id="logo" />
<p id="switcher">
<span>switch theme:</span>
<a href="#">1</a>
<a href="#">2</a>
<a href="#">3</a>
</p>
</div>
<div id="header">
<h1>PHP Variables In PHP</h1>
</div>
<div id="col1">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div id="col2">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</body>
</ html >

I’ve created some content with some navigation that will let us change the template used, a header that we will change the style of and two columns of text.

We’re going to use the querystring to allow us to change the current theme that is used by passing the name value pairs to the same PHP file. We will also want to remember which theme is currently being used so that if you wanted to the theme could be used throughout the rest of the site.

Insert the following PHP code before the doctype declaration:


<?php
 session_start();
 
 if (isset($_GET['template'])) {
 $_SESSION['template'] = $_GET['template'];
 $template = '?template='.$_SESSION['template'];
 } elseif (isset($_SESSION['template'])) {
 $template = '?template='.$_SESSION['template'];
 } else {
 $template = '';
 }
?>

Ok, so here is what that code actually does. Since we are using sessions we first need to start the session. Then we check to see if the querystring contains a value for the variable template. If it does then we assign the session variable template to it’s value. We then create a local variable contatining the string that we will append to the location of the CSS file. This string is a querystring with one name value pair. It will allow us to pass the name of the template we want to use to the PHP file creating the CSS styles. If the querystring does not exist for the page then a template hasn’t been requested. If there is a session we want to pass that value to the PHP file creating the CSS file, otherwise we will just leave the querystring passed to the PHP file creating the CSS blank and the default theme will be used.

Now that we know how we are going to handle requests for the different templates we can change the values of the links to update the template used - AKA the theme switcher. Update the links to include the querystring name of template with the value set to the name of your template.  In this case I’ve just used the numbers 1, 2 and 3.


<p id="switcher">
 <span>switch theme:</span>
 <a href="index.php?template=1">1</a>
 <a href="index.php?template=2">2</a>
 <a href="index.php?template=3">3</a>
 </p>

We also need to update the location of the PHP file creating the CSS. Just append the local variable containing the querystring values:


<link rel="stylesheet" href="css/style.php<?php echo $template; ?>" type="text/css" media="screen" />

Now we are ready to create our PHP file that will handle the creation of our template. There is only line of code that will allow us to do this. We just need to let our server know that we should send this PHP file as the content type of text/css. Do this by including the following on the first line of the style.php file:


header("Content-type: text/css; charset: UTF-8");

Now you can simply use this file as you would do a normal CSS file but with the added benefit of parsing some PHP within it too. This can open up a whole host of options to allow you not only to dynamically change content on the page but also dynamically change the visual appearance of the page.

How I intend to use this is to firstly find out which template we should use. Remember we can receive this information from the querystring. Since I will be expecting a number of the value between 1 and 3 I will do some error checking first to see that the value sent is only one of those values. Otherwise I will apply the default theme - theme number 1.


$numberoftemplates = 3;
if (isset($_GET['template'])) {
 $template = $_GET['template'];
 if ((!is_numeric($template)) || ($template > $numberoftemplates) || ($template < 0)) {
 $template = 1;
 } else {
 $template = round($template);
 }
} else {
 $template = 1;
}

Now I have a local variable named $template that holds the number of template I should be using. For clarity I will echo this out using PHP:


echo '/*====== template used: '.$template.' ======*/';

Visit the style.php page now in the browser and “/*====== template used: 1 ======*/” should be shown. If you change the querystring to style.php?template=2 then the template number 2 will be used.

Since we are not creating entire new CSS files for the different themes we are just going to define some differences between the themes and the main template. We can store these differences into an array like so:


$css = array(
 'header-background'  => array(
 1 => 'url(../images/header-bg-1.jpg) no-repeat',
 2 => 'url(../images/header-bg-2.jpg) no-repeat',
 3 => 'url(../images/header-bg-3.jpg) no-repeat'
 ),
 'header-h1-colour' => array(
 1 => '#fff',
 2 => '#fff',
 3 => '#666'
 ),
 'header-h1-font' => array(
 1 => 'bold normal 35px Helvetica, Arial, sans-serif',
 2 => 'bold normal 35px Trebuchet MS, Arial, sans-serif',
 3 => 'normal normal 35px Georgia, serif'
 )
 );

As you can see, I have defined three elements in the array for each CSS selector I want to change. I have also defined an array as the value for each element in the array allowing me to give each selector a choice of three options depending on which theme we are using.

As an example all we need to do now is echo out the value from the array for our chosen theme into the CSS:


background: <?php echo $css['header-background'][$template]; ?>;

And that’s all that is required. Use this throughout your file to allow you to change lots of visual elements of your site. The full styles I have used are shown below:


* {
margin:0;
padding:0;
}
body {
font-size:.8em;
background:#F3F4F9;
font-family:Arial;
text-align:center;
}
#wrap {
width:990px;
margin:0 auto;
text-align:left;
}
#nav {
padding:10px 0;
width:990px;
overflow:auto;
}
#logo {
float:left;
}
#switcher {
float:right;
width:170px;
text-align:right;
padding:45px 20px 0 0;
}
#switcher span {
float:left;
padding:6px 10px 0 0;
}
#switcher a {
display:block;
float:left;
padding:4px 8px;
border:1px solid #ccc;
background:#eee;
margin:0 0 0 2px;
}
#switcher a:hover {
background:#fff;
}
#header {
clear:both;
background: <?php echo $css['header-background'][$template]; ?>;
height: 206px;
}
#header h1 {
text-align:right;
padding:155px 25px 0 0;
color: <?php echo $css['header-h1-colour'][$template]; ?>;
font:<?php echo $css['header-h1-font'][$template]; ?>;
}
#col1 {
width:450px;
float:left;
margin:20px 0 0 0;
}
#col2 {
width:450px;
float:right;
margin:20px 0 0 0;
}

Download Theme Switcher With PHP Variables In CSS

Enjoy this article?

Your vote will help the site grow and allow me to produce more articles like this.

2 Responses to “Theme Switcher With PHP Variables In CSS”

  1. Cambiare temi con PHP e CSS! | sastgroup.com Says:

    [...] Link: http://blog.adamoliver.net/tutorials/theme-switcher-with-php-variables-in-css/ [...]

  2. Cambiare temi con php e css! Says:

    [...] Link: http://blog.adamoliver.net/tutorials/theme-switcher-with-php-variables-in-css/ [...]

Leave a Reply