Sometimes i need to create a functionality plugin for my site that require certain hooks function from a theme. This is how i do it.
Force To Deactivate Plugin on Activation if the theme is not active.
you just need to add this on your plugin
/* Activation Hook */
register_activation_hook( __FILE__, 'my_plugin_activation_hook' );
/**
* Activation Hook
* force deactivate if not installed in Genbu Theme.
* add notice to user to install Genbu Theme
*
* @since 0.1.0
*/
function my_plugin_activation_hook() {
/* check if genbu theme installed and active */
if ( 'genbu' != get_template() ) {
/* deactivate plugin */
deactivate_plugins( plugin_basename( __FILE__ ) );
/* notice to user */
wp_die( sprintf( __( 'Sorry, you can’t activate unless you have installed <a href="%s">Genbu Theme</a>', 'my-plugin'), 'http://genbutheme.com/' ) );
}
}the function to check current theme is get_template() and if you’re using child theme you can change it to get_stylesheet(). both function return current active theme folder. So if your theme is located in wp-content/themes/your-theme you can change the function above to:
/* check if genbu theme installed and active */
if ( 'your-theme' != get_template() ) {It’s not limited to activation hook. you can also use this conditional in other function. Very usefull if in your plugin you use lots of function from your theme and i prefer this than using conditional check with function_exists for every function.
For example:
/* add it in plugins loaded hook. */
add_action('plugins_loaded','my_plugin_plugins_loaded');
/* all action and filter goes here. */
function my_plugin_plugins_loaded(){
/* check active theme */
if ( 'my-theme' == get_template() ){
add_action( 'something', 'my_plugin_action' );
add_filter( 'something', 'my_plugin_filter' );
}
}
function my_plugin_action(){
$param = my_theme_function();
echo $param;
}
function my_plugin_filter(){
$param = my_other_theme_function();
return $param;
}Check minimum version of Theme.
You can also check your theme version wih wp_get_theme() function:
/* all action and filter goes here. */
function my_plugin_plugins_loaded(){
/* get theme data */
$theme_data = wp_get_theme( get_template() );
$theme_version = $theme_data->get( 'Version' );
/* check active theme is "my-theme" and minimum version is 3.0.0 */
if ( 'my-theme' == get_template() && version_compare( $theme_version, '3.0.0' ) >= 0 ){
add_action( 'something', 'my_plugin_action' );
add_filter( 'something', 'my_plugin_filter' );
}
}