wordpress - youtube视频的结尾

标签 wordpress youtube

我正在尝试找出一种方法,当当前帖子中的youtube视频停止播放时,该方法可以自动转到wordpress网站上的下一个帖子。 youtube视频未嵌入youtube API,而是使用iframe嵌入。

有谁知道如何做到这一点?

最佳答案

我正在从这个答案YouTube iframe API and WordPress修改代码。您必须重写您的帖子才能使用简码或将其修改为当前配置。

使用指向YT ID的短代码[ytplayer id="M7lc1UVf-VE"]嵌入视频,而播放使用YT iFrame API
我们使用 get_next_post() (可以是 get_previous_post() )检查下一个帖子链接,并将其传递给JavaScript代码。视频结束后,如果我们有下一则实际的帖子,它将跳转到链接:

add_shortcode( 'ytplayer', 'print_yt_player' );

function print_yt_player( $atts ) {
    wp_enqueue_script( 'yt-iframe', 'https://www.youtube.com/iframe_api' );
    $yt_id = $atts['id'];
    $next_post = get_next_post();
    $go_next = 'false';
    if (!empty( $next_post )) {
        $next_post = get_permalink($next_post);
        $go_next = 'true';
    } else {
        $next_post = '';
    }

    $html = <<<HTML
        <div id="player"></div>   
        <script>
            var player, done = false;
            function onYouTubeIframeAPIReady() {
                player = new YT.Player('player', {
                    height: '390',
                    width: '640',
                    videoId: '$yt_id',
                    playerVars: { 'autoplay': 1, 'controls': 1 },
                    events: {
                        'onReady': onPlayerReady,
                        'onStateChange': onPlayerStateChange
                    }
                });
            }    
            function onPlayerReady(event) {
                event.target.playVideo();
            }
            function onPlayerStateChange(event) {
                if( event.data == YT.PlayerState.ENDED && $go_next ) 
                    window.location.href = '$next_post';
            }
        </script>
HTML;
    # It's important that the previous line doesn't have ANY whitespace before of after HTML;
    return $html;
}

关于wordpress - youtube视频的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32927499/

相关文章:

html - 无论屏幕大小如何,媒体查询都会触发

wordpress - 在 Woocommerce 结帐表单中输入会导致浏览器报告 SSL 问题

android - YouTube API 3上传视频-无效的凭据-Android

ios - 将 youtube 视频嵌入 UIView/UIWebView

java - 如何使用Java检索超过25个YouTube评论

iphone - Web View 中的 YouTube - iPhone

html - 需要通过 css 更改 html 值,如下所述。我使用的是wordpress,所以不好编辑核心文件

wordpress - Algolia - Wordpress - 从索引中排除类别

javascript - 删除未使用的 Javascript base.js (Youtube iframe api)

css - 如何使 Logo 保持居中并随着浏览器调整大小而缩小以适合