WordPress trick: Change theme programatically

WordPress trick: Change theme programatically

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.

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress trick: Change theme programatically

Leave a Reply

Your email address will not be published.