您可以使用global
object wp
用于访问 YouTube 播放器功能。 YouTube 视频在twentyseventeen theme
loads wp-自定义-header.js https://github.com/WordPress/WordPress/blob/master/wp-includes/js/wp-custom-header.js#L384文件并在 384 行创建新对象。
这是您可以使用的一些解决方案:
var ww_timer = setTimeout(function ww_video() {
if(wp.customHeader.handlers.youtube.player == null){
ww_timer = setTimeout(ww_video, 50);
}else {
if(typeof wp.customHeader.handlers.youtube.player.unMute === "function") {
wp.customHeader.handlers.youtube.player.unMute();
wp.customHeader.handlers.youtube.player.stopVideo();
}else{
ww_timer = setTimeout(ww_video, 50);
}
}
}, 50);
这段代码转到my_js.js
文件(我在活动子主题的主目录中创建了它。您可以将此代码添加到另一个.js
,如果有的话)您活跃的子主题。另外,我们还需要更新functions.php
使用此代码的文件:
function ww_youtube_functions(){
wp_enqueue_script('ww_youtube_video',get_stylesheet_directory_uri().'/my_js.js',array('wp-custom-header'),false, true);
}
add_action('wp_enqueue_scripts', 'ww_youtube_functions');
此代码的必需部分是array('wp-custom-header')
:将具有脚本依赖性的脚本放入队列wp-custom-header
.
setTimeout
不是最好的方法。我相信,可以用更优雅的代码来完成。
但它经过测试并且有效。