Skip to content

Commit

Permalink
Refactor theme previews (#50338)
Browse files Browse the repository at this point in the history
* Theme Previews: Refactor theme preview hooks to reduce code duplication

* fix PHPCS

* fix PHPCS
  • Loading branch information
scruffian authored May 4, 2023
1 parent 23c6c1a commit 9b821f5
Showing 1 changed file with 17 additions and 22 deletions.
39 changes: 17 additions & 22 deletions lib/compat/wordpress-6.3/theme-previews.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,27 @@
*/

/**
* Filters the blog option to return the directory for the previewed theme.
* Filters the blog option to return the path for the previewed theme.
*
* @param string $current_stylesheet The current theme directory.
* @return string The previewed theme directory.
* @param string $current_stylesheet The current theme's stylesheet or template path.
* @return string The previewed theme's stylesheet or template path.
*/
function gutenberg_theme_preview_stylesheet( $current_stylesheet = null ) {
$preview_stylesheet = ! empty( $_GET['theme_preview'] ) ? $_GET['theme_preview'] : null;
$wp_theme = wp_get_theme( $preview_stylesheet );
if ( ! is_wp_error( $wp_theme->errors() ) && current_user_can( 'switch_themes' ) ) {
return sanitize_text_field( $preview_stylesheet );
function gutenberg_get_theme_preview_path( $current_stylesheet = null ) {
// Don't allow non-admins to preview themes.
if ( ! current_user_can( 'switch_themes' ) ) {
return;
}

return $current_stylesheet;
}

/**
* Filters the blog option to return the parent theme directory for the previewed theme.
*
* @param string $current_stylesheet The current theme directory.
* @return string The previewed theme directory.
*/
function gutenberg_theme_preview_template( $current_stylesheet = null ) {
$preview_stylesheet = ! empty( $_GET['theme_preview'] ) ? $_GET['theme_preview'] : null;
$wp_theme = wp_get_theme( $preview_stylesheet );
if ( ! is_wp_error( $wp_theme->errors() ) && current_user_can( 'switch_themes' ) ) {
return sanitize_text_field( $wp_theme->get_template() );
if ( ! is_wp_error( $wp_theme->errors() ) ) {
if ( current_filter() === 'stylesheet' ) {
$theme_path = $wp_theme->get_stylesheet();
} elseif ( current_filter() === 'template' ) {
$theme_path = $wp_theme->get_template();
}

return sanitize_text_field( $theme_path );
}

return $current_stylesheet;
Expand Down Expand Up @@ -124,8 +119,8 @@ function block_theme_activate_nonce() {
* Attaches filters to enable theme previews in the Site Editor.
*/
if ( ! empty( $_GET['theme_preview'] ) ) {
add_filter( 'stylesheet', 'gutenberg_theme_preview_stylesheet' );
add_filter( 'template', 'gutenberg_theme_preview_template' );
add_filter( 'stylesheet', 'gutenberg_get_theme_preview_path' );
add_filter( 'template', 'gutenberg_get_theme_preview_path' );
add_filter( 'init', 'gutenberg_attach_theme_preview_middleware' );
}

Expand Down

0 comments on commit 9b821f5

Please sign in to comment.