Using WordPress ‘after_switch_theme’ PHP action

The after_switch_theme WordPress PHP action fires on the first WP load after a theme switch if the old theme still exists.

Usage

add_action('after_switch_theme', 'your_custom_function', 10, 2);

function your_custom_function($old_name, $old_theme) {
    // your custom code here
}

Parameters

  • $old_name (string): Old theme name.
  • $old_theme (WP_Theme): WP_Theme instance of the old theme.

More information

See WordPress Developer Resources: after_switch_theme

Examples

Clear cache after theme switch

Clears the cache when the theme is switched.

add_action('after_switch_theme', 'clear_cache_on_theme_switch', 10, 2);

function clear_cache_on_theme_switch($old_name, $old_theme) {
    // Clear cache
    wp_cache_flush();
}

Updates theme-related options when the theme is switched.

add_action('after_switch_theme', 'update_theme_options', 10, 2);

function update_theme_options($old_name, $old_theme) {
    // Update theme options
    update_option('some_theme_option', 'new_value');
}

Notify admin about theme switch

Sends an email notification to the admin when the theme is switched.

add_action('after_switch_theme', 'notify_admin_theme_switch', 10, 2);

function notify_admin_theme_switch($old_name, $old_theme) {
    // Send email notification
    $to = get_option('admin_email');
    $subject = 'Theme switched on your WordPress site';
    $message = 'The theme has been switched from ' . $old_name . ' to ' . get_option('stylesheet');
    wp_mail($to, $subject, $message);
}

Backup old theme settings

Backs up the old theme’s settings when the theme is switched.

add_action('after_switch_theme', 'backup_old_theme_settings', 10, 2);

function backup_old_theme_settings($old_name, $old_theme) {
    // Backup theme settings
    $theme_mods = get_option("theme_mods_$old_name");
    update_option("backup_theme_mods_$old_name", $theme_mods);
}

Perform custom actions on theme switch

Performs custom actions when the theme is switched.

add_action('after_switch_theme', 'custom_actions_on_theme_switch', 10, 2);

function custom_actions_on_theme_switch($old_name, $old_theme) {
    // Perform custom actions
}