DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

In WordPress, changing themes are easy. But what when you have to change a theme programmatically? Just read the following recipe to find out. It’s a lot easier than you may think!

The first thing you have to do is to paste the following function in your functions.php file.

function switchTheme($theme) {
    global $wpdb;
    if (isset($theme)) {
        $queries = array("UPDATE wp_options SET option_value = 'default' WHERE option_name = 'template';", "UPDATE wp_options SET option_value = 'default' WHERE option_name = 'stylesheet';", "UPDATE wp_options SET option_value = 'default' WHERE option_name = 'current_theme';");
        foreach ($queries as $query){
            $wpdb->query($query);
        }
    }
}

What I’ve done in the function was simply to update the wp_options table (change the prefix if necessary) with a new theme name. You probably noticied that I used queries in a loop, which isn’t a good practice. There’s for sure a better way to do it but since I’m not a SQL expert I can’t get anything better. If you know how to achieve the same effect without using looped queries, don’t hesitate to leave me a comment!

Once you’ve pasted the function in your functions.php file, you can call it, for example using a filter. The $theme parameter is the theme name. For example default to restore the good old Kubrick theme.

Tags

6 Comments

  1. Thanks for the post!

    One way to remove the loop is to convert the multiple queries into one:

    $query = “UPDATE wp_options SET option_value = ‘default’ WHERE option_name IN (‘current_theme’, ‘template’, ‘stylesheet’)”;

    $wpdb->query($query);

    —-

  2. But, this change is for all access to the web or just for the related session? Is it posible to have 2 or 3 themes (for example) and apply them in different conditions as different categories, different editors, etc…?

  3. I want to make a wordpress theme gallery with the preview theme functionality on theme thumbnails. how can i implement this?

  4. Not the best advice. There`s switch_theme(). Also, you should use the global $wpdb; $wpdb->prefix instead and do a $wpdb->prepare() for the query.

  5. You need to call ‘switch_theme(“Whatever”)’

    Doing the database query (updating wp_options, as above) on it’s own is unlikely to be sufficient as most themes have an installer which executes additional queries on the database.

Leave a Comment

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