Inspired by Nick Lewis, making it easier to embed and save more time.
Last active
November 11, 2022 12:10
-
-
Save ChrisButterworth/2b6988238addf632cf6b4f7d7c4a0d0e to your computer and use it in GitHub Desktop.
Lazy html only YouTube embed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function youtube_embed($id = null) { | |
// Return if id isn't set | |
if (!$id) | |
return; | |
// Get title - seems overkill | |
$title = explode('</title>', explode('<title>', file_get_contents("https://www.youtube.com/watch?v=".$id))[1])[0]; | |
// Open buffer and compile HTML | |
ob_start(); | |
?><iframe | |
width="560" | |
height="315" | |
src="https://www.youtube.com/embed/<?= $id; ?>" | |
srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto;}span{height:2em;text-align:center;font:48px/2 sans-serif;color:white;text-shadow:0 0 0.5em black;}</style><a href='https://www.youtube.com/embed/<?= $id; ?>?autoplay=1' role='button' aria-label='Play video' title='Play video'><img src='https://img.youtube.com/vi/<?= $id; ?>/0.jpg' alt='<?= $title; ?>' /><span>▶</span></a>" | |
frameborder="0" | |
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" | |
allowfullscreen | |
title="<?= $title; ?>" | |
loading="lazy" | |
></iframe><?php | |
// Return compiled HTML | |
return ob_get_clean(); | |
} | |
echo youtube_embed('7V8oFI4GYMY'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment