Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Embedded YouTube Video, Create Link that Jumps to Specific Time

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>';
}
like image 607
devbanana Avatar asked Feb 06 '17 05:02

devbanana


People also ask

How do I link to a specific time in a YouTube video?

The Right-Click Menu in YouTube is Your Friend Right click within the YouTube video frame. From the right-click menu, select “get video URL at current time.” Now, paste the URL to wherever you are sharing the link. When this URL is clicked, it will forward to the time you specified.


Video Answer


1 Answers

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>
like image 122
devbanana Avatar answered Oct 04 '22 17:10

devbanana