Quick WordPress Theme Switcher Plugin Tutorial

Posted in Coding, JS & AJAX, PHP, Tutorials • Posted on 9 Comments

The design or theme of a website plays a vital role in its success. Recent changes in popular sites prompted me to write this tutorial. Facebook Timeline, Youtube Dark Theme and Gmail Clean and simple design are major changes made recently. Also 1stwebdesigner is going through its redesign process and the changes looks promising from a users perspective.

In this tutorial I am going to explain how you can dynamically switch WordPress themes based on various conditions allowing you to provide the best possible user experience. Before we dig into dynamic theme switching, let’s see how WordPress changes its menu in the admin dashboard.

Theme Switcher Plugin

File Download

Where’s the demo? It would be nicer if you download the file and test it on your own, that way you’ll understand things more!

Change WordPress Theme using Dashboard

WordPress admin dashboard provides the functionality to change themes using the Appearance menu. You can activate new themes by clicking the activate link under each theme. You may know that this theme activation will be applied across all the pages and content without any restriction. But we are seeking dynamic theme changing which allows different themes based on different conditions. This is not possible with default WordPress features. But the theory behind theme activation is going to be important for us. So let’s see how it works.

Process of Theme Activation

You may have activated several themes for testing purposes. But do you know how WordPress keeps the active theme?

There are 3 options in the wp_options table called template, stylesheet and current_theme which are used to keep the current theme. Whenever you activate a new theme, these 3 options will get updated in the database. Following are some sample values for before activating theme and after activating theme.

Before Activating

template – twentyeleven
stylesheet – twentyeleven
current_theme – twentyeleven

After Activating

template – press-work
stylesheet – press-work
current_theme – Presswork

In the above options, template and stylesheet contain the name of your theme folder and current_theme contains the theme name defined in the stylesheet. When a new theme is activated, the above options will be changed permanently in the database. Hence it is not suitable for dynamic theme switching. So let’s see how we can change themes dynamically.

Switching Themes using WordPress Filters


Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen.

WordPress.org

So we can assign filters on template and stylesheet options to call a function which will handle the dynamic theme switching functionality. The following code shows you how to add filters on theme options.

Note: in case you’re wondering where you should include all the code below, place everything in your index.php file. Or simply download the zip file and check.

add_filter('template', 'your_function_name');
add_filter('stylesheet', 'your_function_name');

function your_function_name($theme) {

}

Whenever the above 2 options are called, your function will be called automatically and you can do the theme modifications inside the function.

Creating the Theme Switcher Plugin

You might know that WordPress has a predefined comment structure in the plugin file to get the information about the plugin. So we will create a folder in the /wp-content/plugins directory as switch-theme. These are the details of the plugin to be  included in the top of the plugin file.

<?php

/*
Plugin Name: Switch Themes
Version: 1.0
Author URI: -
Plugin URI: -
Description:  Switch themes dynamically.
Author: Rakhitha Nimesh
License: GPL2
*/

?>

Now let’s see how we can change the themes based on certain conditions.

Change Theme Based on Browser

There are some browsers which do not fully support CSS3 features, HTML5 , and jQuery animation. So when we want to create a new theme for our site we have to consider all the browser’s compatibility issues. Generally we create a design compatible with all browsers. Hence we have to limit the amazing effects provided by current design libraries. Now with this theme changing functionality, you can provide different themes with effects based on browser.

<?php

add_filter('template', 'switch_theme_by_browser');
add_filter('stylesheet', 'switch_theme_by_browser');

function switch_theme_by_browser($theme) {

    $browser = $_SERVER['HTTP_USER_AGENT'];

    if(preg_match('/MSIE/i',$browser) && !preg_match('/Opera/i',$browser))
    {
        $theme = "twentyeleven";
    }
    elseif(preg_match('/Firefox/i',$browser))
    {
        $theme = "twentyten";
    }
    elseif(preg_match('/Chrome/i',$browser))
    {
        $theme = "sliding-door";
    }
    elseif(preg_match('/Safari/i',$browser))
    {
        $theme = "presswork";
    }
    elseif(preg_match('/Opera/i',$browser))
    {
        $theme = "fotofolio";
    }
    elseif(preg_match('/Netscape/i',$browser))
    {
        $theme = "colorway";
    }

    return $theme;
}

?>
  • We get the user environment related information using HTTP_USER_AGENT.
  • Then we can use regular expressions to match the browser and assign a different theme.
  • Finally the modified theme will be returned instead of the current theme.

You can decide which effects to include in themes based on browser.

Change Theme Based on User Device

In our modern world, mobile based devices such as android ,blackberry ,iPhone are becoming much more popular to use to browse the internet. Most sites are developing mobile friendly themes to improve the user interaction. We can use dynamic theme changing to provide an appropriate theme based on users browsing device.

<?php

add_filter('template', 'switch_theme_by_device');
add_filter('stylesheet', 'switch_theme_by_device');

function switch_theme_by_device($theme){

	$useragent = $_SERVER['HTTP_USER_AGENT'];

	if (preg_match('/ipad/',strtolower($useragent))) {
        	$theme = 'twentyeleven';
    	}
	elseif (preg_match('/iphone/',strtolower($useragent))) {
        	$theme = 'twentyten';
    	}
	elseif (preg_match('/blackberry/',strtolower($useragent))) {
        	$theme = 'colorway';
    	}
	elseif (preg_match('/android/',strtolower($useragent))) {
        	$theme = 'simplio';
    	}

	return $theme;

}

?>

As we did previously, we can use simple regular expressions to match the browsing devices and change the themes dynamically.

The above methods are straightforward and the user does not have any control in theme changing. Let’s go for something more interesting.

Switch between Old and New Look

New Look
New Theme

Old Theme

Old Theme

When a site changes its theme and comes up with a new look, its sometimes difficult for the users to adjust instantly. Many web sites allow both new and old look until transition is done smoothly (Gmail,Facebook). So I am going to show you how you can allow the users to switch between Old and New themes according to their preferences. Let’s get started.

Create Switch Link

First I’ll show you how to create a link for theme switching. I am going to add this to the top of your header.

<?php

function switch_to_old_theme_footer() {

?>

	<style>
		#switcherPanel{
			background: none repeat scroll 0 0 #FFFFFF;
    			border-color: #CFCFCF #CFCFCF #CFCFCF -moz-use-text-color;
    			border-style: solid solid solid none;
    			border-width: 1px 1px 1px medium;
    			font-weight: bold;
    			padding: 10px;
    			width: 150px;
			position:absolute;
			top:30px;
			left:0px;
		}
	</style>
	<p id="switcherPanel"><a href="javascript:void(0);" onclick="switch_theme();" ></a></p>

<?php
}
add_action('wp_head', 'switch_to_old_theme_footer');

function switch_to_old_theme_scripts() {
    $plugin_dir = WP_PLUGIN_URL . "/";

    wp_enqueue_script( 'jquery' );
    wp_register_script( 'switchjs', $plugin_dir ."switch-theme/switcher.js");
    wp_enqueue_script( 'switchjs' );

}

add_action('wp_enqueue_scripts', 'switch_to_old_theme_scripts');

?>

The above code inserts a switch link to the header using the wp_head action hook with some basic CSS styles. Also I have added necessary js scripts using wp_enqueue_scripts action hook. Lets see what happens when the switch link is clicked.

<script>
var switch_theme = function(){

	var act_theme = readCookie('acttheme');

	if(act_theme == ''){
		setCookie('acttheme','old',1);
	}
	else if(act_theme == 'new'){
		setCookie('acttheme','old',1);
	}
	else if(act_theme == 'old'){
		setCookie('acttheme','new',1);
	}

	window.location.href = 'http://www.example.com/'; /* change this to your website's URL */

};

var setCookie = function(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)+ ";path=/;expires="+expire.toGMTString();
};

var readCookie = function(cookieName) {
 var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
 var sMatch = (' '+document.cookie).match(re);
 if (cookieName && sMatch) return unescape(sMatch[1]);
 return '';
};
</script>
  • Initially, the switch_theme function will be called and it checks for a cookie named acttheme using readCookie method. readCookie and setCookie are common methods widely used in getting cookie information.
  • Initially acttheme cookie value will be empty. So we assign the value of old. Cookies will be used to track the current theme after user clicks the switch link.
  • Then we redirect the user to the home page. We toggle the value of acttheme cookie whenever user clicks the switch link.

Now the cookie is set. Let’s see how we provide the old and new look.

<?php

add_filter('template', 'switch_to_old_theme');
add_filter('stylesheet', 'switch_to_old_theme');

function switch_to_old_theme($theme) {

    if(isset($_COOKIE['acttheme']) && $_COOKIE['acttheme'] == 'old'){
	$theme = 'twentyeleven';
    }else{
	$theme = 'sim-plo';
    }

    return $theme;
}

?>

We call a function using add_filter on template and stylesheet options. Then we check the cookie value of acttheme. Based on the cookie value we switch the theme. So the user will have the option to view the old theme as well as the new theme. Use only one of the above methods since using more will generate errors on your pages. Make sure to setup the path of your site in the switcher.js file.

WordPress dynamic theme switching is a great method to provide better user experience by providing a look and feel according to the users preferences. Hope you enjoyed the tutorial and we’d like to know any other scenarios where you might use dynamic theme switching.

22 Written ArticlesWebsiteGoogle+

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on WordPress Web Application Development. He is a regular contributor to 1stWebDesigner, Tuts+ network and Sitepoint network. Make sure to contact him at www.innovativephp.com or follow him on Twitter and Google+

9 Comments Best Comments First
  • SocialJeev

    Sunday, July 1st, 2012 23:07

    2

    I have installed the plugin and successfully able to use without any problem. Thanks for the useful plugin

    I have a few doubts which you can help with :

    1) If the plugin has the option to let any user to switch a theme, does it affect any server or website performace ? Because each effort they make to switch the theme is equal to activate a new theme ( I guess)

    2) Any plan to make the plugin settings be available on dashboard to manage the options? Like device settings etc.
    3) Also do you plan to implement like switching style in addition with theme . Ex : http://css-tricks.com/examples/AlternateStyleSheets/

    Thank you !

    +1
    • Rakhitha Nimesh

      Monday, July 2nd, 2012 07:19

      3

      Thank you for the comment.

      1) Its actually not equal to Activating a theme. When we activate a theme, the details are saved in the database. So we need to get details from database in each request. But in this technique I am using a cookie value in users browser. Every time user changes the theme we look for cookie value in browser instead of database. So it will not generate considerable performance issues.

      2) No plans yet for providing dashboard options page. It can be created easily if necessary.

      3) Since we are activating new themes every time it will be a different style sheet. SO switching style wont be necessay. If someone has a special requirement to switch style sheets inside a single theme, we will be able to implement it as well.

      Hope you got answers for your questions. Feel free to ask any other questions you have or my answers are not clear.

      0
      • SocialJeev

        Monday, July 2nd, 2012 09:46

        4

        Hi Nimesh ,

        Thanks for your quick response and clarifying my doubts .

        >2) No plans yet for providing dashboard options page. It can be created easily if necessary.

        a) I think dashboard settings page will be more comfortable to everyone. Hope you implement it in future versions

        b) Usually your plugin helps us to view frontend on small screen devices like mobile or ipad. But do you have any plan to help us making the dashboard be viewable/ compatible on all screens? We have responsive themes and plugins like yours with front end compatibility for small screen devices. But no plugin or theme is available for dashboard yet.

        3) If someone has a special requirement to switch style sheets inside a single theme, we will be able to implement it as well.

        Switching style will be very necessary for the people who use black backgrounds for webpages. For example, I customized a theme and made it a style with black screen. Some visitors may not like black screen but I need that. So an option to let the visitors be chose in between white, black and minimal colors will be brilliant. I have tried the css-tricks tutorial. But no luck with it. So it is necessary for enthusiasts like me

        Your plugin is already a multi-functional and I appreciate your effort. Hope you consider my requests

        Thanks a lot

        0
        • Rakhitha Nimesh

          Tuesday, July 3rd, 2012 00:51

          5

          Hi

          a) Dashboard page will be very important since you have to change theme names in plugin code at the moment. I have to consider building a options page.

          b)Good question. Actually I haven’t thought about it and I haven’t seen that kind of functionality yet. It will be much more difficult than this. Definitely I am going to try it and maybe publish it with a follow up article to this one.

          c) In your scenario switching styles is a very good feature too. I have seen it on themes at themeforest. Hope to implement this functionality in future.

          Thanks for the ideas.

          0
  • Abdul Malek

    Friday, June 29th, 2012 10:33

    1

    WOow. Its a great blog. Those who want to learn web designing must read this blog. Congrats for your blog.

    0
  • Kirby

    Friday, August 17th, 2012 13:46

    6

    Hi Rakhitha Nimesh,

    just want to ask, is there a way that we can just switch themes using the function “Change Theme By Device” and still have a the switch link.

    thanks

    -1
    • Rakhitha Nimesh

      Tuesday, August 28th, 2012 20:39

      7

      I think we should be able to do it. I have to check whether its possible. But it will get too complicated with lot of conditions. Hence users will not understand what is going on and why separate themes are displayed.

      -1
  • shawn

    Friday, September 14th, 2012 00:58

    8

    The biggest problem I see with this approach is when your themes have different sidebars and menus activated.

    Is there currently any way of defining active widgets in each active sidebar, and the same for menus for each theme on the server?

    Example:
    My theme has 3 different sidebars, header, left, right, so I setup my theme with the widgets I want in each sidebar.
    Twentyten does not have a header sidebar, thus no widgets go in there.

    Usually when I activate the twentyten theme, setup my widget areas, and then return to using my theme, I have to reset all my widget areas and menus as well.

    How do you get around this problem?

    -1
    • Rakhitha Nimesh

      Saturday, September 15th, 2012 06:03

      9

      Actually that would be a problem. If the defined widget areas of all the themes are not common you cannot use this technique.

      -1
  • shawn

    Friday, September 14th, 2012 00:58

    8

    The biggest problem I see with this approach is when your themes have different sidebars and menus activated.

    Is there currently any way of defining active widgets in each active sidebar, and the same for menus for each theme on the server?

    Example:
    My theme has 3 different sidebars, header, left, right, so I setup my theme with the widgets I want in each sidebar.
    Twentyten does not have a header sidebar, thus no widgets go in there.

    Usually when I activate the twentyten theme, setup my widget areas, and then return to using my theme, I have to reset all my widget areas and menus as well.

    How do you get around this problem?

    -1
    • Rakhitha Nimesh

      Saturday, September 15th, 2012 06:03

      9

      Actually that would be a problem. If the defined widget areas of all the themes are not common you cannot use this technique.

      -1
  • Kirby

    Friday, August 17th, 2012 13:46

    6

    Hi Rakhitha Nimesh,

    just want to ask, is there a way that we can just switch themes using the function “Change Theme By Device” and still have a the switch link.

    thanks

    -1
    • Rakhitha Nimesh

      Tuesday, August 28th, 2012 20:39

      7

      I think we should be able to do it. I have to check whether its possible. But it will get too complicated with lot of conditions. Hence users will not understand what is going on and why separate themes are displayed.

      -1
  • SocialJeev

    Sunday, July 1st, 2012 23:07

    2

    I have installed the plugin and successfully able to use without any problem. Thanks for the useful plugin

    I have a few doubts which you can help with :

    1) If the plugin has the option to let any user to switch a theme, does it affect any server or website performace ? Because each effort they make to switch the theme is equal to activate a new theme ( I guess)

    2) Any plan to make the plugin settings be available on dashboard to manage the options? Like device settings etc.
    3) Also do you plan to implement like switching style in addition with theme . Ex : http://css-tricks.com/examples/AlternateStyleSheets/

    Thank you !

    +1
    • Rakhitha Nimesh

      Monday, July 2nd, 2012 07:19

      3

      Thank you for the comment.

      1) Its actually not equal to Activating a theme. When we activate a theme, the details are saved in the database. So we need to get details from database in each request. But in this technique I am using a cookie value in users browser. Every time user changes the theme we look for cookie value in browser instead of database. So it will not generate considerable performance issues.

      2) No plans yet for providing dashboard options page. It can be created easily if necessary.

      3) Since we are activating new themes every time it will be a different style sheet. SO switching style wont be necessay. If someone has a special requirement to switch style sheets inside a single theme, we will be able to implement it as well.

      Hope you got answers for your questions. Feel free to ask any other questions you have or my answers are not clear.

      0
      • SocialJeev

        Monday, July 2nd, 2012 09:46

        4

        Hi Nimesh ,

        Thanks for your quick response and clarifying my doubts .

        >2) No plans yet for providing dashboard options page. It can be created easily if necessary.

        a) I think dashboard settings page will be more comfortable to everyone. Hope you implement it in future versions

        b) Usually your plugin helps us to view frontend on small screen devices like mobile or ipad. But do you have any plan to help us making the dashboard be viewable/ compatible on all screens? We have responsive themes and plugins like yours with front end compatibility for small screen devices. But no plugin or theme is available for dashboard yet.

        3) If someone has a special requirement to switch style sheets inside a single theme, we will be able to implement it as well.

        Switching style will be very necessary for the people who use black backgrounds for webpages. For example, I customized a theme and made it a style with black screen. Some visitors may not like black screen but I need that. So an option to let the visitors be chose in between white, black and minimal colors will be brilliant. I have tried the css-tricks tutorial. But no luck with it. So it is necessary for enthusiasts like me

        Your plugin is already a multi-functional and I appreciate your effort. Hope you consider my requests

        Thanks a lot

        0
        • Rakhitha Nimesh

          Tuesday, July 3rd, 2012 00:51

          5

          Hi

          a) Dashboard page will be very important since you have to change theme names in plugin code at the moment. I have to consider building a options page.

          b)Good question. Actually I haven’t thought about it and I haven’t seen that kind of functionality yet. It will be much more difficult than this. Definitely I am going to try it and maybe publish it with a follow up article to this one.

          c) In your scenario switching styles is a very good feature too. I have seen it on themes at themeforest. Hope to implement this functionality in future.

          Thanks for the ideas.

          0
  • Abdul Malek

    Friday, June 29th, 2012 10:33

    1

    WOow. Its a great blog. Those who want to learn web designing must read this blog. Congrats for your blog.

    0

Comments are closed.

54.83.172.112 - unknown - unknown - US