Is it possible to stop a theme activation when a certain plugin is not activated

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

Leave a Comment

tech