The question:
I’d like to be able to check if the twentytwelve theme is active. I know if I was checking for an active plugin I’d do something like:
$active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );
if ( in_array( 'plugin-folder/plugin-folder.php', $active_plugins ) ) {
//do stuff
} else {
add_action( 'admin_notices', 'create-a-notice' );
}
What’s the proper way to check if a theme is active so I can run a function for that theme?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
You can use wp_get_theme
:
<?php
$theme = wp_get_theme(); // gets the current theme
if ( 'Twenty Twelve' == $theme->name || 'Twenty Twelve' == $theme->parent_theme ) {
// if you're here Twenty Twelve is the active theme or is
// the current theme's parent theme
}
Or, you can simply check if a function in twentytwelve exists — which is likely less reliable; a plugin, or even another theme, could declare twentytwelve_setup
, for instance.
<?php
if ( function_exists( 'twentytwelve_setup' ) ) {
// Twenty Twelve is the current theme or the active theme's parent.
}
Method 2
if( 'twentytwelve' == get_option( 'template' ) ) {
// do something
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0