Get YouTube video ID from helper

Hi,

I have a url field in my project for editors to add a YouTube or Vimeo video url to, and am then usingHtml::video to generate an iframe, my code for this is below:

      <?php
      $options = [
        'vimeo' => [
          'portrait' => 0,
          'title' => 0,
          'byline' => 0,
          'playsinline' => 1,
          'loop' => 1,
          'background' => 1,
          'muted' => 1,
          'controls' => 0,
        ],
        'youtube' => [
          'color' => 'white',
          'playsinline'=> 1,
          'rel'=> 0,
          'loop' => 1,
          'controls' => 0,
          'autoplay' => 1,
          'mute' => 1,
        ],
      ];
      $attr = [
        'class' => 'grayscale',
      ];
      ?>

<?php if($page->bannerVideoUrl()->isNotEmpty()): ?>
  <?= Html::video($page->bannerVideoUrl(),$options,$attr) ?>
<?php endif ?>

I now need to access the video id if the url used is a YouTube one, to add the following to the options:

'playlist' => {videoId}

This is needed otherwise the loop option will not be respected (more info on that here: YouTube Embedded Players and Player Parameters  |  YouTube IFrame Player API  |  Google for Developers). Can Kirby help me access the id from the video, or do I need to do some regex on the url to extract it?

You can use the Uri class:

dump((new Kirby\Http\Uri('https://www.youtube.com/watch?v=PajT4qyE55c'))->query()->v);
1 Like

Perfect, just the job. Thank you!