Reputation: 507
On Wordpress, I'm trying to embed a YouTube video, then include links that jump to specific times in that video. So if I want to jump to 2:00, I can create a link that jumps to that point in the embedded video.
I found a similar question from a few years ago, but I believe the YouTube API has changed. I cannot find any plugins that can do this, so want to do it on my own if possible.
Suggestions?
Edit: Here is the code I've come up with so far. However, the only issue is that if the video hasn't been played yet, then seekTo seems to take a long time. I'm not sure if I should response to the onReady event, or another.
add_action( 'wp_enqueue_scripts', 'register_yt_frameapi' );
function register_yt_frameapi() {
wp_register_script( 'frameapi', 'https://www.youtube.com/iframe_api', array(), '1.0.0', true );
}
add_shortcode('ytlink', 'ytlink');
function ytlink($atts, $content = null)
{
wp_enqueue_script('frameapi');
$id = $atts['id'];
$time = $atts['time'];
$timeParts = explode(':', $time);
$seconds = 0;
for ($i = 0; count($timeParts); $i++)
{
$seconds += array_pop($timeParts) * 60 * $i;
}
return '<a href="javascript:void(0);" ' .
'onclick="var player = new YT.Player(\''.$id.'\', {events: {onReady: function () {player.seekTo('.$seconds.', true);}}});">'.
($content ?? $time) . '</a>';
}
Upvotes: 6
Views: 4874
Reputation: 507
Okay, I got this figured out finally. I'll post my solution here in case anyone else has the same question. I don't know if there may be a better way to do this, but this is the best I found.
Javascript:
var player;
var ytSeconds = 0;
jQuery(document).ready(function ()
{
player = new YT.Player('yt-embed', {events: {
'onStateChange': onPlayerStateChange
}
});
});
function onPlayerStateChange(e)
{
if (e.data == 1 && ytSeconds > 0) {
e.target.seekTo(ytSeconds);
ytSeconds = 0;
}
}
function seekTo(seconds)
{
if (player.getPlayerState() == 1) {
player.seekTo(seconds);
}
else {
ytSeconds = seconds;
player.playVideo();
}
}
Then links just look like:
<a href="#" onclick="seekTo(120);">02:00</a>
Upvotes: 8
Reputation: 609
You can use the embed code like this. Use ?start=100&end=250
<iframe width="560" height="315" src="https://www.youtube.com/embed/N8VCzpXJZvM?start=100&end=250&autoplay=1" frameborder="0" allowfullscreen></iframe>
Upvotes: 0
Reputation: 777
There are good samples.
https://12starsmedia.com/blog/embed-youtube-video-specific-start-time http://www.youtubestartend.com/
You can use ?start= to define start points
Upvotes: -1