How to Remove WordPress Themes: A Step-by-Step Guide

Home » Snippets » How to Remove WordPress Themes: A Step-by-Step Guide
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Have you ever installed a WordPress theme, only to find out that it’s not what you were looking for? Or maybe you have too many themes installed and you want to remove the ones you no longer use. Whatever the reason may be, it’s important to know how to properly remove WordPress themes from your site. In this article, we’ll guide you through the steps to remove a WordPress theme, and also share some tips on how to choose the best themes for your site.

					function wpturbo_remove_theme() {
    $theme = wp_get_theme();
    if ( 'twentytwenty' === $theme->name || 'twentytwenty' === $theme->parent_theme ) {
        $error = __( 'Sorry, you cannot delete the default WordPress theme.', 'wpturbo' );
        wp_die( $error, '', array( 'response' => 403 ) );
    } else {
        $theme_slug = $theme->get_stylesheet();
        $deleted = wp_delete_theme( $theme_slug );
        if ( $deleted ) {
            $message = __( 'Theme deleted successfully.', 'wpturbo' );
        } else {
            $message = __( 'Could not delete theme.', 'wpturbo' );
        }
        wp_redirect( admin_url( 'themes.php' ) . '?message=' . urlencode( $message ) );
    }
}
				

The code snippet above is a function called wpturbo_remove_theme() which is responsible for removing a WordPress theme. It contains a set of conditional statements that check if the theme being deleted is the default WordPress theme, and if it is, the function will prompt an error message that the default theme cannot be deleted. This is done to prevent accidental deletion of the default theme, which can have serious consequences.

On the other hand, if the theme being deleted is not the default theme, then the function proceeds to delete the theme. This is done by retrieving the theme stylesheet using the get_stylesheet() method and passing it to the wp_delete_theme() function. If the deletion is successful, the function sets a success message using the _e() WordPress function. If the deletion fails, an error message is set instead.

At the end, the function redirects the user back to the themes.php screen. This is done using the wp_redirect() function, which takes the URL of the screen and the success/error message as parameters. The success/error message is encoded using the urlencode() function to make sure special characters are properly escaped.

Overall, this function provides a safe and practical way of deleting WordPress themes without accidentally deleting the default theme.

Register an account to save your snippets or go Pro to get more features.