How to create a shortcode to let the user add the ID of a YouTube video?
-
16-10-2019 - |
Question
I use the following to add in a post a YouTube thumbnail and display the video in a fancybox:
<div><a class="fancybox" href="#video2">
<img src="http://img.youtube.com/vi/dm36W5NTPag/0.jpg" alt="Welcome To High Output" width="220px" height="120px" /></a></div>
<div id="video2" style="display: none;">
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="480" height="390" src="http://www.youtube.com/embed/dm36W5NTPag" frameborder="0"
allowFullScreen></iframe></div>
Basically the shortcode must have one fields to enter the ID of the video in the thumbnail, the link to the video, the link of the first div, and the id of the second div.
http://img.youtube.com/vi/(HERE)/0.jpg
and http://img.youtube.com/vi/(HERE)/0.jpg
<a class="fancybox" href="#(HERE)">
and <div id="(HERE)" style="display: none;">
So the shortcode should look like:
[youtube VIDEO ID:(Enter ID)]
Does anybody know how to do this?
Solution
add_shortcode('youtube', 'youtube_shortcode');
function youtube_shortcode($atts){
if(!isset($atts[0])) return;
$id = strip_tags($atts[0]);
ob_start();
?>
<div><a class="fancybox" href="#video_<?php echo $id; ?>">
<img src="http://img.youtube.com/vi/<?php echo $id; ?>/0.jpg" alt="Welcome To High Output" width="220px" height="120px" /></a></div>
<div id="video_<?php echo $id; ?>" style="display: none;">
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="480" height="390" src="http://www.youtube.com/embed/<?php echo $id; ?>" frameborder="0"
allowFullScreen></iframe></div>
<?php
return ob_get_clean();
}
use it like: [youtube "dm36W5NTPag"]
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange