主题的外部实时预览/wp-admin/themes.php
页面,从tmpl主题生成:
<script id="tmpl-wpse" type="text/template">
...cut...
<div class="theme-actions">
<# if ( data.active ) { #>
<# if ( data.actions.customize ) { #>
<a class="button button-primary customize load-customize hide-if-no-customize" href="{{{ data.actions.customize }}}"><?php _e( \'Customize\' ); ?></a>
<# } #>
<# } else { #>
<a class="button button-secondary activate" href="{{{ data.actions.activate }}}"><?php _e( \'Activate\' ); ?></a>
<a class="button button-primary load-customize hide-if-no-customize" href="{{{ data.actions.customize }}}"><?php _e( \'Live Preview\' ); ?></a>
<# } #>
</div>
...cut...
</script>
我们可以通过
wp_prepare_themes_for_js
滤器
下面是一个示例:
/**
* External Live Previews
*/
add_filter( \'wp_prepare_themes_for_js\', function( $prepared_themes )
{
//--------------------------
// Edit this to your needs:
$externals = [
\'twentysixteen\' => \'http://foo.tld/demo/twentysixteen/\',
\'twentyfifteen\' => \'http://bar.tld/demo/twentyfifteen/\'
];
//--------------------------
foreach( $externals as $slug => $url )
{
if( isset( $prepared_themes[$slug][\'actions\'][\'customize\'] ) )
$prepared_themes[$slug][\'actions\'][\'customize\'] = $url;
}
return $prepared_themes;
} );
但由于
load-customize
类,它将触发一个单击事件并打开一个iframe覆盖:
$(\'#wpbody\').on( \'click\', \'.load-customize\', function( event ) {
event.preventDefault();
// Store a reference to the link that opened the Customizer.
Loader.link = $(this);
// Load the theme.
Loader.open( Loader.link.attr(\'href\') );
});
当我们单击带有外部url的实时预览按钮时,它将触发如下错误:
Uncaught SecurityError:未能执行\'pushState
\' 关于“History”:URL为的历史状态对象http://foo.tld/demo/twentysixteen/
\' 无法在来源为“”的文档中创建http://example.tld
\' 和URL\'http://example.tld/wp-admin/themes.php
\'.
我们可以通过双击(不是真正可靠的选项)或删除load-customize
为外部预览链接初始化。这里有一个这样的黑客:
/**
* Remove the .load-customize class from buttons with external links
*/
add_action( \'admin_print_styles-themes.php\', function()
{ ?>
<script>
jQuery(document).ready( function($) {
$(\'.load-customize\').each( function( index ){
if( this.host !== window.location.host )
$( this ).removeClass( \'load-customize\' );
} );
});
</script> <?php
} );
我从哪里得到的
this.host
来自@daved的想法
here.
另一个更激进的方法是推翻tmpl-theme
样板