Halloween Sale 15% off Ends in See the plans
PHP

Preview Another Theme as an Administrator

Lets administrators view the site with another installed theme by adding ?wpide_theme=theme-folder to any address, while visitors keep seeing the active theme.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_preview_theme = function () {
    static $theme = null;

    if ( null !== $theme ) {
        return $theme;
    }

    $theme = false;

    if ( empty( $_GET['wpide_theme'] ) || ! function_exists( 'wp_get_current_user' ) || ! current_user_can( 'switch_themes' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        return $theme;
    }

    $candidate = wp_get_theme( sanitize_file_name( wp_unslash( $_GET['wpide_theme'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

    if ( $candidate->exists() && ! $candidate->errors() ) {
        $theme = $candidate;
    }

    return $theme;
};

add_action( 'setup_theme', function () use ( $wpide_preview_theme ) {
    add_filter( 'stylesheet', function ( $stylesheet ) use ( $wpide_preview_theme ) {
        $theme = $wpide_preview_theme();
        return $theme ? $theme->get_stylesheet() : $stylesheet;
    } );

    add_filter( 'template', function ( $template ) use ( $wpide_preview_theme ) {
        $theme = $wpide_preview_theme();
        return $theme ? $theme->get_template() : $template;
    } );
}, 1 );

Notes

Use the theme's folder name, for example ?wpide_theme=twentytwentyfour. The choice lasts for that page view only.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.