
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!

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.
2 Responses
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);
—-
Bad advice. See also http://codex.wordpress.org/Function_Reference/switch_theme
Trackbacks: