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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.