Using WordPress ‘check_theme_switched()’ PHP function

The check_theme_switched() WordPress PHP function checks if the theme of a WordPress website has been changed. If a change is detected, it runs the ‘after_switch_theme’ hook on the next WordPress load.

Usage

Let’s say you’ve changed your WordPress theme and want to execute some operations right after the theme switch. Here’s how you might use the check_theme_switched() function:

if ( is_admin() && false !== get_option( 'theme_switched' ) ) {
    check_theme_switched();
}

In this example, we’re checking if we’re in the WordPress admin area and if the ‘theme_switched’ option is set (i.e., the theme has been changed). If both conditions are met, we call the check_theme_switched() function.

Parameters

The check_theme_switched() function doesn’t take any parameters.

More Information

See WordPress Developer Resources: check_theme_switched()

This function was implemented in WordPress 3.3.0. As of the last update (September 2021), it’s not deprecated.

Examples

Display a notice after a theme switch

Suppose you want to display a notice to the admin after a theme switch. You could do this by adding a function to the ‘after_switch_theme’ action, like so:

add_action( 'after_switch_theme', 'my_theme_switch_notice' );

function my_theme_switch_notice() {
    add_action( 'admin_notices', 'my_theme_switch_admin_notice' );
}

function my_theme_switch_admin_notice() {
    echo '<div class="notice notice-success is-dismissible">';
    echo '<p>Your theme has been changed successfully!</p>';
    echo '</div>';
}

In this example, when a theme switch is detected, the my_theme_switch_notice() function will be triggered. This function adds another function, my_theme_switch_admin_notice(), to the ‘admin_notices’ action. The second function displays a notice in the WordPress admin area.

Reset a custom theme option after a theme switch

Suppose your theme has a custom option that should be reset whenever the theme is switched. Here’s how you could handle that:

add_action( 'after_switch_theme', 'reset_my_custom_option' );

function reset_my_custom_option() {
    update_option( 'my_custom_option', 'default_value' );
}

In this example, when a theme switch is detected, the reset_my_custom_option() function is triggered. This function resets the ‘my_custom_option’ value to ‘default_value’.

Please replace ‘my_custom_option’ and ‘default_value’ with your actual option name and default value.

Delete a transient after a theme switch

If you’re using transients in your theme and you want to delete a specific transient after a theme switch, you can do it like this:

add_action( 'after_switch_theme', 'delete_my_transient' );

function delete_my_transient() {
    delete_transient( 'my_transient' );
}

In this example, when a theme switch is detected, the delete_my_transient() function is triggered. This function deletes the ‘my_transient’ transient.

Please replace ‘my_transient’ with your actual transient name.