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:

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.

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.

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

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

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

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:

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:

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.

59 Comments

  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

    Reply
  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?

    Reply
  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

    Reply
  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?

    Reply
  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!

    Reply
  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?

    Reply
  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).

    Reply
  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!

    Reply
  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.

    Reply
  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!

    Reply
  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.

    Reply
    • 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.

      Reply
  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?

    Reply
    • 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

      Reply
  13. 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!

    Reply
  14. 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? 🙂

    Reply
  15. 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?

    Reply
  16. 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’]);}
    }

    Reply
  17. 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.

    Reply
  18. 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.

    Reply
    • 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).

      Reply
      • 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

        Reply
      • 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

        Reply
        • 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.

          Reply
  19. Hey I stumbled upon this and its the only write-up I could find on the topic,
    I get a bunch of errors when following this to the t, do you have an updated code or maybe some other sources where I can get more info?

    Reply
    • I’m sorry but this is a really old tutorial. There maybe another one that does this functionality elsewhere.

      Reply

Leave a Reply to Keith Cancel reply