Active theme responds to theme change request to alert user

I’m usually a fan of doing this kind of work on the server-side since it’s far too easy to circumvent JavaScript on the client-side with modern debugging tools, but this is a unique problem and this may fit your use case (depending on who your audience is).

Using pure JavaScript, you can do this:

  • Create a JavaScript file in the root of your theme directory and name it “upload.js”
  • Add the following code to it (and be sure to read the comments):

    (function($) {
        $(function() {
    
        // Check to verify that we're on the "Install Themes" page
        var $upload = $('#install-theme-submit');
        if($upload.length > 0) {
    
            // Watch for the user to click on the upload button
            $upload.click(function(evt) {
    
                // When they do, get the name of the file they've uploaded
                var sFilePath = $('input[type=file]').val();
                var aFilePath = sFilePath.split('\\');
                sFilePath = aFilePath[aFilePath.length - 1];
    
                // If it's equal to updated, let them know:
                if(sFilePath.toLowerCase() === 'upgrader.zip') {
    
                    // Create a WordPress-style notification and add it to the screen
                    $('h4').before(
                        $('<div />')
                            .append(
                                $('<p />')
                                    .text("Do not upload this file.")
                            ).attr('class', 'updated')
                    );
    
                    // Stop the upload
                    evt.preventDefault();
    
                } // end if
    
            });
    
        } // end if
    
    });
    })(jQuery);
    
  • Add the following to your theme’s functions.php. This will load the script into your theme:

    function custom_upload_script() {
    
        wp_register_script('admin-upload-script', get_template_directory_uri() . '/upload.js');
        wp_enqueue_script('admin-upload-script');
    
    } // end custom_upload_script
    add_action('admin_enqueue_scripts', 'custom_upload_script');
    

If you’re looking to go pure server-side, there’s no hook for managing the theme activation action; however, you may be able to take advantage of the switch_theme action. This is pure speculation but once the action fires you may be able to read some information from within the file then revert back to the previously used theme.

Leave a Comment