So I am planning a theme that will depend on a plugin (for instance Timber or Themosis).
So of course a theme will break if it can’t use it’s depending plugin’s. So I would like a way to stop the user of activating a theme that needs a certain plugin to work and instead show an friendly error message containing the plugin that’s needed.
So far I found out how to check if a plugin is installed or not (link), but how to stop the theme from being activated if that’s possible at all?
I also found out about the switch_theme
and the after_switch_theme
actions.
So what I am missing right now is a way to stop the actual activation. Is this possible?
edit:
Found this for displaying admin notices/warnings.
4 Answers
Using after_switch_theme
will activate the theme (which is fine as we want to run the check within the context of the new theme).
If the dependencies are not fulfilled ($missing_dependencies = true;
) we’re instantly switching back to the theme previously used (passed via after_switch_theme
and $oldtheme
).
add_action( 'after_switch_theme', 'check_theme_dependencies', 10, 2 );
function check_theme_dependencies( $oldtheme_name, $oldtheme ) {
if ( $missing_dependencies ) :
// Update default admin notice: Theme not activated.
add_filter( 'gettext', 'update_activation_admin_notice', 10, 3 );
// Custom styling for default admin notice.
add_action( 'admin_head', 'error_activation_admin_notice' );
// Switch back to previous theme.
switch_theme( $oldtheme->stylesheet );
return false;
endif;
}
function update_activation_admin_notice( $translated, $original, $domain ) {
// Strings to translate.
$strings = array(
'New theme activated.' => 'Theme not activated.'
);
if ( isset( $strings[$original] ) ) {
// Translate but without running all the filters again.
$translations = get_translations_for_domain( $domain );
$translated = $translations->translate( $strings[$original] );
}
return $translated;
}
function error_activation_admin_notice() {
echo '<style>#message2{border-left-color:#dc3232;}</style>';
}
You can use the snippet above within your functions.php
, but make sure that after_switch_theme
is called before the required dependencies.
Update: There does not seem to be an easy way to prevent the admin notice triggered via the switch_theme
function. Overwriting the message via the gettext
filter seems to be a good workaround.
Thanks to @alpipego for telling me how to overwrite strings in WordPress Core 🙂
Further reading: Changing Core WordPress Strings