Powered By Blogger

lunes, 2 de julio de 2012

Quick WordPress Theme Switcher Plugin Tutorial

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.



No hay comentarios: