switch_themeaction-hookWP 1.5.0

Fires when the theme is switched. Used when deactivating a theme.

Fires after the theme has been switched but before the next request — the redirect. When a theme is activated, a redirect to the same page occurs.

During this event, only functions from the old theme being switched away from are available. If functions from the new theme are needed, use after_switch_theme.

Use this hook when something must be done while a theme is being deactivated.

See after_switch_theme for the details and step-by-step behavior of theme switching.

Usage

add_action( 'switch_theme', 'wp_kama_switch_theme_action', 10, 3 );

/**
 * Function for `switch_theme` action-hook.
 * 
 * @param string   $new_name  Name of the new theme.
 * @param WP_Theme $new_theme WP_Theme instance of the new theme.
 * @param WP_Theme $old_theme WP_Theme instance of the old theme.
 *
 * @return void
 */
function wp_kama_switch_theme_action( $new_name, $new_theme, $old_theme ){

	// action...
}

Parameters

$new_name(string)
The new theme name.
$new_theme(WP_Theme)
The new theme's WP_Theme object. See wp_get_theme().
$old_theme(WP_Theme)
The old theme's WP_Theme object.

Examples

#1 Delete theme options when it is deactivated

add_action('switch_theme', 'mytheme_del_options');
function mytheme_del_options( $old_name ) {
	delete_option('mytheme_options');
}

#2 Delete options on theme deactivation and add them on activation

// Delete theme settings on deactivation
add_action('switch_theme', 'deactivate_my_theme');
function deactivate_my_theme( $old_name ){
	// Old theme functions are available, but new theme functions are not

	delete_option('mytheme_options');
}

// Add theme settings on activation
add_action('after_switch_theme', 'activate_my_theme' );
function activate_my_theme( $new_name ){
	// New theme functions are available, but old theme functions are not

	$opt = array('opt1'=>'val1', 'opt2'=>'val2');

	add_option('mytheme_options', $opt );
}

Changelog

Since 1.5.0 Introduced.
Since 4.5.0 Introduced the $old_theme parameter.

Where the hook is called

switch_theme()
switch_theme
wp-includes/theme.php 875
do_action( 'switch_theme', $new_name, $new_theme, $old_theme );

Where the hook is used in WordPress

wp-includes/default-filters.php 374
add_action( 'switch_theme', 'wp_clean_theme_json_cache' );