end of youtube video

I’m trying to come up figure out a way to automatically go to to the next post in line on a wordpress site when a youtube video in the current post has stopped playing. The youtube videos are not embeded with the youtube API but rather embeded using the iframe.

Does anyone have any idea how to do this?

Related posts

1 comment

  1. I’m adapting the code from this answer YouTube iframe API and WordPress. You’d have to rewrite your posts to use a shortcode or adapt the idea to your current configuration.

    Videos are embeded using a shortcode pointing to the YT ID: [ytplayer id="M7lc1UVf-VE"], and the playback uses YT iFrame API.
    We check the next post link using get_next_post() (could be get_previous_post()) and pass that to the JavaScript code. When the video ends, and if we have an actual next post, it will jump to the link:

    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;
    }
    

Comments are closed.