-
How to programmatically embed YouTube video using iFrame
Posted by markzero on Monday, December 12th, 2011
First of all: Be sure to put the following code INSIDE THE LOOP! YouTube videos can be embedded into your posts and/or pages using custom fields. This way (or similar, like meta boxes) is good for your clients so they can put their own stuff to a site.
Something similar to this:

You can decide whether to put just the ID of a YouTube video, or the whole thing… Next we put this code into While loop:
<?php $vid1=get_post_meta($post->ID, "video_url_id_1", true); ?>
And now you put an iFrame:
<iframe id="med-vid-1" width="640" height="355" src="http://www.youtube.com/embed/<?php echo $vid1; ?>?&rel=0" frameborder="0" allowfullscreen></iframe>
Be sure to encode HTML characters like & => &amp;
Also, be sure to use /embed URL. IFrames are better than objects, because they are HTML5 ready. Downside is, they are not (yet) as strong with YouTube Javascript API as objects.
Again: DON’T FORGET THE LOOOOP! ;) (if (have_posts()) : while (have_posts()) : the_post(); … endwhile; endif;)
Posted in: PHP, Wordpress, YouTube.
Share this story:
Leave a Reply
Useful Links
Categories
Archives














