Add a Style Switcher to your WordPress Theme

Whenever I download a WordPress theme there’s hardly ever a time that I leave it as is. Almost for sure – I will have to change some things to customize according to the site’s identity. For instance, maybe I’d want to match the heading styles to a company logo, or change the background colors to have the same schema or simply change the link styles to have a sharper look. Wouldn’t it be nice to have the ability to change all of this by switching style sheets from the theme options?

This tutorial will show you how to create a simple style switcher from your themes options panel. It will have a single drop down list with all the available styles to pick from. Once saved – your theme will switch to the selected style. Ready to get started – let’s begin:

Part 1 – Set up functions.php

First thing you need is a functions.php file. A functions file is an optional “plugin” type of file you can include in your theme directory folder. One of its’ purpose is to setup administration options for your theme – which is exactly what we’re doing. Create a file and name it “functions.php” and paste the code below. Note that you need to change variables that define your theme name ($themename) and the short name ($shortname) to match your themes:

<?php
 
$themename = "My Sweet Theme";
$shortname = "mst";
$options = array (
array( "name" => "Style Sheet",
	"desc" => "Enter the Style Sheet you would like to use for Sweet Ass Theme",
	"id" => $shortname."_style_sheet",
	"type" => "select",
	"options" => array("default", "green", "blue", "yellow"),
	"std" => "default"),
);
?>

The above code initializes your theme options structure. First it defines several variables, including a multi-dimensional array (which will become our drop down list containing the four selectable options that will dictate our style sheets). Next is to copy the code below. This code loops through each iteration of the array we declared previously. It assigns a type of form field, displays labels and applies the correct descriptions etc. It also includes several functions that saves the form data, resets information and displays status messages etc. It’s a wee bit technical – so its better if we simply copy and paste the code.

 
<?php
function mytheme_add_admin() {
 
global $themename, $shortname, $options;
 
if ( $_GET['page'] == basename(__FILE__) ) {
 
if ( 'save' == $_REQUEST['action'] ) {
 
foreach ($options as $value) {
update_option( $value['id'], $_REQUEST[ $value['id'] ] ); }
 
foreach ($options as $value) {
if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ]  ); } else { delete_option( $value['id'] ); } }
 
header("Location: themes.php?page=functions.php&saved=true");
die;
 
} else if( 'reset' == $_REQUEST['action'] ) {
 
foreach ($options as $value) {
delete_option( $value['id'] ); }
 
header("Location: themes.php?page=functions.php&reset=true");
die;
 
}
}
 
add_theme_page($themename." Options", "".$themename." Options", 'edit_themes', basename(__FILE__), 'mytheme_admin');
 
}
 
function mytheme_admin() {
 
global $themename, $shortname, $options;
 
if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>';
 
?>
<div class="wrap">
<h2><?php echo $themename; ?> Settings</h2>
 
<form method="post">
 
<?php foreach ($options as $value) {
switch ( $value['type'] ) {
 
case "open":
?>
<table width="100%" border="0" style="background-color:#eef5fb; padding:10px;">
 
<?php break;
 
case "close":
?>
 
</table><br />
 
<?php break;
 
case "title":
?>
<table width="100%" border="0" style="background-color:#dceefc; padding:5px 10px;"><tr>
<td valign="top" colspan="2"><h3 style="font-family:Georgia,'Times New Roman',Times,serif;"><?php echo $value['name']; ?></h3></td>
</tr>
 
<!--custom-->
 
 
<?php break;
case "sub-title":
?>
<h3 style="font-family:Georgia,'Times New Roman',Times,serif; padding-left:8px;"><?php echo $value['name']; ?></h3>
<!--end-of-custom-->
 
 
<?php break;
 
case 'text':
?>
 
<tr>
<td valign="top" width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
<td width="80%"><input style="width:400px;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>" /></td>
</tr>
 
<tr>
<td><small><?php echo $value['desc']; ?></small></td>
</tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>
 
<?php
break;
 
case 'textarea':
?>
 
<tr>
<td valign="top" width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
<td width="80%"><textarea name="<?php echo $value['id']; ?>" style="width:400px; height:200px;" type="<?php echo $value['type']; ?>" cols="" rows=""><?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?></textarea></td>
 
</tr>
 
<tr>
<td><small><?php echo $value['desc']; ?></small></td>
</tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>
 
<?php
break;
 
case 'select':
?>
<tr>
<td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
<td width="80%"><select style="width:240px;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>"><?php foreach ($value['options'] as $option) { ?><option<?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option><?php } ?></select></td>
</tr>
 
<tr>
<td><small><?php echo $value['desc']; ?></small></td>
</tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>
 
<?php
break;
 
case "checkbox":
?>
<tr>
<td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
<td width="80%"><?php if(get_option($value['id'])){ $checked = "checked="checked""; }else{ $checked = "";} ?>
<input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> />
</td>
</tr>
 
<tr>
<td><small><?php echo $value['desc']; ?></small></td>
</tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr>
 
<?php break;
 
}
}
?>
 
<p class="submit">
<input name="save" type="submit" value="Save changes" />
<input type="hidden" name="action" value="save" />
</p>
</form>
<form method="post">
<p class="submit">
<input name="reset" type="submit" value="Reset" />
<input type="hidden" name="action" value="reset" />
</p>
</form>
 
<?php
}
add_action('admin_menu', 'mytheme_add_admin');
?>

Test out your theme options by going under the “Appearance” section > “Your Theme Name Options” tab. You will see the drop down list with the selectors already in place. Once you hit “Save Changes” – it saves your data. While clicking “Reset” sets it back to the default selector. We also see nice status messages appear on top each time we update.

style-sheet-switcher1

Part 2 – Create the Style Sheets

Create four .css files that correspond to the drop down list selections we defined in our functions.php. The names do not have to exactly match the selectors (but is wise to have some meaningful relation to the names). Save these four files in the root directory of your theme:

style.css – this style sheet is for a black background page with white colored fonts.

/* CSS Document */
body {background:#000000; color:#FFFFFF;}

green.css – this style sheet is for a green background page with white colored fonts.

/* CSS Document */
body {background:#3bae09; color:#FFFFFF;}

blue.css – this style sheet is for a blue background page with white colored fonts.

/* CSS Document */
body {background:#038aba; color:#FFFFFF;}

yellow.css – this style sheet is for… you get the picture.

/* CSS Document */
body {background:#f6f658; color:#333333;}

Part 3 – The Switch Statement

Now that we have our options working in the back end, and we have our four style sheets sitting in the root folder waiting to be called, all we need now is a way to flip the style sheets in our header file. We achieve this by using a standard switch statement. A switch statement in php is an alternative to the the “if…else” statement. It uses the case keyword which we use to match our selectors to execute a statement that calls the appropriate style sheet. In the default header.php file – look for the line of code below and delete it:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />

This is the standard call for the default style.css file which we no longer need. Next, paste the code below inside your header.php file:

<?php
	global $options;
	foreach ($options as $value) {
		if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] ); }
	}
	?>
	<?php switch ($mst_style_sheet) {
		 case "default":?>
		<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
	<?php break; ?>
	<?php case "green":?>
		<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/green.css" type="text/css" media="screen" />
	<?php break; ?>
	<?php case "blue":?>
		<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/blue.css" type="text/css" media="screen" />
	<?php break; ?>
	<?php case "yellow":?>
		<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/yellow.css" type="text/css" media="screen" />
	<?php break; ?>
	<?php }?>

The above code is quite self explanatory. First it grabs whichever values we’ve stored in our theme options. Second – is the switch statement for our drop down list, followed by cases for each entry – with its unique statement calling the style sheets.

Now if you go back to your style switcher and select “blue” – your theme style should switch to blue – and so on and so forth.

You can have as many styles as you wish to integrate in your options. As well as the amount of customization in the actual .css files is completely up to you. You can download the source files from this link – simply add these files in your theme folder and change some values – and your theme will instantly have it’s own style switcher.

57 thoughts on “Add a Style Switcher to your WordPress Theme”

  1. Being new to WP (3 blogs) and really NOT all that interested in learning the code (inside & out) your information is really helpful.

    I downloaded the Kubrick-on-Crack theme and am working with it for a site re-work. The ability to change styles, etc will be helpful.

    Thanks,
    Ed

  2. Hi,

    Thanks for the tutorial. Would you know why I am getting “Parse error: syntax error, unexpected $end in /home/smallbiz/public_html/blog/wp-content/themes/default/functions.php on line 107″ after updating my functions file with the first 2 peices of code above?

  3. Great tutorial I am new to WordPress themes and php code but would make one observation for others.

    If your theme already has a functions.php, mine has and I do not want to change to much, so I will just create a folder called custom and drop the new file into this folder, and it is then easy to add to any other theme.

    Then in the main functions.php I add a single line at the top:
    include_once(TEMPLATEPATH.”/custom/functions.php”);

    Hi Michael:
    One thing I was wondering if it could be more dynamic, have a styles folder and add the css files in there, then the admin function looks in this folder and adds the file names as options, then in the header.php use the if get_option(‘mst_style_sheet’) to return any active css file name.

    This could cut down the code in the header.php to two lines.

    But I am not up to speed enough with php to do this, so it is just a suggestion to make your fantastic tutorial more dynamic.

    David

  4. I really like this tutorial it worked great. I’m only running into one problem. Since I added this feature to my functions, anytime I hit a button that performs an action the page goes white. The action gets performed, however, the page is not redirected properly.

    Anyone else run into this?

  5. Great script.
    It would be nice if visitors could switch the themes as well.
    So I wonder how to change the script from accepting also the GET method and how to display it as a widget. Any hint would be greatly appreciate!

  6. I’m tryign to get this to work with a twenty ten child theme. The options show in the admin, but the style doesn’t seem to change on the site. Any ideas why?

  7. Is there a way to use this for CSS in WordPress? I’ve looked every where for a solution but haven’t found one yet (that actually works).

  8. this is what im looking for almost half day. have try many other tutorial but no luck. i will try my best to follow this tutorial and give a feedback about the result. thank you!

  9. This is the tutorial I was looking since so long. Thank you so much for this tutorial. I was looking for header code to switch css.

    I have one more issue with switching the category from select option in theme panel. can you please help me for that too?
    I am using same array as you described here for css. Issue is I dont know what code I should add to my theme file to switch or select the catagory to display post on the home column or my area.
    Thanks again.

  10. Just wanted to say thanks for this tutorial. I’ve been working on a Specky Geek tutorial for theme options, but I couldn’t figure out the php to call my CSS drop down. Finally got it to work, thanks to you. After I’m finished with my theme and it is (hopefully) accepted to the WordPress Theme Directory, I’ll post a link here.

    Thanks again!

  11. Is there a way to make this option available for visitors to the site? I would like visitors to be able to choose 1 of 2 designs by choosing an option to switch the style sheets.

    1. i think you’re need more of a javascript enabled option that will change the css right on the page, and maybe keep that information inside a session in the server. its possible – but this is not the route. do a search on javascript style switcher in google. pls post your findings.

  12. Thanks for this nice tutorial. But I have a problem with it. When I chose the option in the theme settings panel It doesn´t save it, and it stays allways on default. Do I have to do some file writable or something?

    1. ok ok ok
      I only made the mistake of putting the “default” option on the last position on the array, I didn´t think it was important to have it on the first place!
      Thanks

  13. I spent I while trying to find a plugin that had this functionality. But this was easy to setup and works great! Thanks a lot!

  14. Hi,
    When I place the switch code into the header and reload it onto the browser, I do not see the stylesheets when I view source (and obviously, my site is unstyled) I have cut and pasted this a few times and no error is being thrown. I’m using wp 3.2.1 – Would love to get this working so if anyone experienced this as well I’d love to know what you did to have them appear. Thanks!

    1. My mistake! I had renamed a variable and had forgotten to rename it in the header code. So sweet! Thanks for sharing this!!

  15. Thanks for the great tutorial…one question. Along with the stylesheet option, I want to be able to have them list a company name in the theme options menu and have it post in the header. I’ve tried numerous ways to do this and I can’t get it to display….help? :)

  16. I got this error – Warning: Invalid argument supplied for foreach() in …/header.php on line 38 – All pages are working fine except the main. Please tell me what could be wrong?

  17. This is line 38 – foreach ($options as $value) {
    if (get_settings( $value[‘id’]) === FALSE) {$$value[‘id’] = $value[‘std’]; } else {$$value[‘id’] = get_settings($value[‘id’]);}
    }

  18. I get an Message after saving/resetting which says something like “You don´t have the permission to enter this site”

    I translated it into german and put it into a new file called css_switcher.php which i included (.Templatepath…) in my functions.php.

    Here is a paste of the “new” code: http://pastebin.com/RSsPBDem

    I can´t find the issue.

  19. Think I got this working the way it was intended. Problem – looking at source I see the path to the alt stylesheet points to the parent theme. I’m trying to get this working in a child-theme. Any way to do that? Any help greatly appreciated.

    1. according to the codex:

      Within child themes, both get_bloginfo(‘template_url’) and get_template() will return the parent theme directory. Consider using get_template_directory_uri() instead (for the parent template directory) or get_stylesheet_directory_uri() (for the child template directory).

      1. I got everything working locally. After uploading to 1and1 server I get multiple errors when trying to submit changes withing the wordpress dashboard. On log out get an entire page of errors.
        here is first 3 lines of 17 lines of errors:
        Warning: Cannot modify header information – headers already sent by (output started at /homepages/8/d282856630/htdocs/wp-content/themes/test2/functions.php:6) in /homepages/8/d282856630/htdocs/wp-login.php on line 362

        Warning: Cannot modify header information – headers already sent by (output started at /homepages/8/d282856630/htdocs/wp-content/themes/test2/functions.php:6) in /homepages/8/d282856630/htdocs/wp-login.php on line 374

        Warning: Cannot modify header information – headers already sent by (output started at /homepages/8/d282856630/htdocs/wp-content/themes/test2/functions.php:6) in /homepages/8/d282856630/htdocs/wp-includes/pluggable.php on line 697

      2. Hi

        I am getting exactly the same problem as FREDOG. Except it happens when i try and save or reset my theme settings choice. It looks right in the backend and shows my alternate styles but that’s all.

        I have zapped all the white spaces and spare lines and it ends up telling me the error is on line 1 (which of course at this point is just one huge string of code). And the problem is still there :(

        any other thoughts?

        thanks

        James

        1. the code is a bit messy due to the html and php combined. what has helped me is that i put that large chunk on code all the way to the bottom of the functions, and not putting anything below. also mind the spaces.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>