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