Tuesday 29 April 2014

Plugin To Switch Themes Conditionally

WordPress already includes a function which enables you to switch themes:
<?php fb_widget( $stylesheet ) ?>
The only problem is, this function will write to your database.
If you need to change themes conditionally, another solution is to use the stylesheet & template filters in WordPress which you can add to a simple plugin like this.

<?php
/**
 * Plugin Name: FB Widget
 * Plugin URI:  http://wordpress.org/plugins/fb-widget
* Description: Description Goes here….
* Version:     1.0
 * Author:      Geeta Dhamija
 * @copyright 2014 DYC
 * Author URI:  http://dreamyourcareer.com/author/geeta-dyc/
 */

add_filter( 'stylesheet', 'wpsites_change_themes' );
add_filter( 'template',   'wpsites_change_themes' );
function wpsites_change_themes( $theme ) {
    if ( ! is_user_logged_in() )
        $theme = 'twentyfourteen';
    return $theme;
}
The above example will display the Twenty Fourteen parent theme to all logged out users and display whatever theme you have activated in the backend to all logged in users.

How To Use This Code

You’ll need to create a plugin with this code then install and activate it.
  1. Create a new file named plugin.php using a code editor like Notepad++ and copy the PHP code from the view raw link in the Gist labelled plugin.php.
  2. For the readme.txt file you can simply use notepad to create a new file named readme.txt and paste the text into the new file.

Then all you need to do is place both files in a new folder and send it to zip so you can upload, install & activate the plugin.

No comments:

Post a Comment