Categories
Tutorials WordPress

Simple video embedding with custom fields in WordPress – YouTube

Creating a custom video field in WordPressOne of my primary goals when building WordPress themes for my clients is to make it as easy as possible for them to post and manage content. And though video embedding has become much simpler over the years, controlling the video content can still be a bit of a pain, especially if you can’t remember the width of your content or if you have an index page where you want to showcase video thumbnails rather than the actual video.

To simplify the process I usually resort to a custom meta box but the technique works just as well with custom fields.

This is the first of two tutorials on this topic and here I’ll be focusing on YouTube videos and oEmbed. The next tutorial will be on self-hosted videos and VideoJS.

Auto-Embedding YouTube videos with a custom field

Consider the following scenario: You have a design that calls for videos to be embedded outside of the main content, for example by placing it above the headline. This is becoming more and more common, and provides both a better user experience and easier access to the important content in the post. The problem of course is that regular video embedding puts the video in the post body, and that’s not what we want. Enter the custom field option.

First thing first: In the post you want to present the video, create a new custom field with the name video_url and the value set to a normal YouTube video ID (the illegible part at the end of the video URL).

Now you have a custom field carrying the YouTube video value. The next step is to dump it into your theme so WordPress can display it. For this we’re going to use the built in oEmbed functionality in WordPress which when used normally lets you dump in a YouTube URL and then automagically inserts the embed code. But in our case we’re adding the URL dynamically in the theme so we are going to use the wp_oembed_get() function a function. The end result is the code you see below:


<?php
// Get the video URL and put it in the $video variable
$videoID = get_post_meta($post->ID, 'video_url', true);
// Echo the embed code via oEmbed
echo wp_oembed_get( 'http://www.youtube.com/watch?v=' . $videoID ); 
?>

The code above places the embed code dynamically generated from the YouTube URL wherever the code is placed in your theme (this of course has to go inside the loop).

Making it conditional

Normally I wrap the code above in divs to control the behavior and place the video where I want it. Because I’m neurotic about clean code I insist on always using conditionals in cases like this to avoid leaving empty divs lying around when no video was added through the custom field. With the conditional added the code gets a bit expanded, but works the same way:


<?php
// Get the video URL and put it in the $video variable
$videoID = get_post_meta($post->ID, 'video_url', true);
// Check if there is in fact a video URL
if ($videoID) {
	echo '<div class="videoContainer">';
	// Echo the embed code via oEmbed
	echo wp_oembed_get( 'http://www.youtube.com/watch?v=' . $videoID ); 
	echo '</div>';
}
?>

Now the video will display wherever you place the code on the provision a video URL was actually added with a custom field.

Getting a video thumbnail from YouTube

So far we’ve just made a fancy way of embedding videos, and it might seem a bit superfluous to do so seeing as you can just add the video right in the post body. But there’s a reason you may want to do it this way: What if you want to make an index page of all your video posts but you want to show the video thumbnail directly from YouTube instead of the video itself? To do this you need the video ID and you also need a bit of PHP magic.

The code below goes inside the loop on an index page and produces the video thumbnail wrapped in a link to the post:


<?php 
// Calls up the YouTube video thumbnail or, if no URL is provided, the featured image from WordPress

// Add a container and a link around the video
echo '<div class="tinyVideoThumb">';
echo '<a href="' . get_permalink() . '" title="Go to ' . the_title() . '" rel="bookmark">';

if ( $video_url ) { // if there is a video URL
	
	// Get the video URL from custom field
	$videoID = get_post_meta($post->ID, 'video_url', true); 
	// Query YouTube for video meta data
	$thumb_query_url = 'http://gdata.youtube.com/feeds/api/videos/' . $videoID . '?v=2&alt=jsonc';
	// Decode the json data from YouTube and put it in a readable format
	$json = json_decode(file_get_contents( $thumb_query_url ));
	// Echo out the thumbnail, give it height and weight and set the alternate description to post title
	echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="60" height="45" alt="' . the_title() . '">';
	echo '</a>';
	echo '</div>';				
						
} else { // else use the standard featured image
											
	the_post_thumbnail('tinyThumb', array('alt' => $postTitle, 'title' => $postTitle)); 
												
} 
?>

The above of course only works for YouTube videos, and only if they are entered with the full URL and none of the other junk that often comes along with YouTube video URLs. You could make a strict rule to only plug in the actual YouTube video ID in the field. If so you could omit the substr() function.

By Morten Rand-Hendriksen

Morten Rand-Hendriksen is a staff author at LinkedIn Learning and lynda.com specializing in WordPress and web design and development and an instructor at Emily Carr University of Art and Design. He is a popular speaker and educator on all things design, web standards and open source. As the owner and Web Head at Pink & Yellow Media, a boutique style digital media company in Burnaby, BC, Canada, he has created WordPress-based web solutions for multi-national companies, political parties, banks, and small businesses and bloggers alike. He also contributes to the local WordPress community by organizing Meetups and WordCamps.

46 replies on “Simple video embedding with custom fields in WordPress – YouTube”

Or you just paste the URL in tinymce since the_content() supports oEmbed already. Just paste the link, YouTube or Vimeo, on a single row (no formatting, no link) and it will auto embed.

Hi Morten,

This is exactly the code I need. Everything seems to work well except! displaying the youtube video.. .. !!

Simply put, the conditional statement works. When I echo “videoID” it displays the correct string. Even the is present; but it is completely empty!?

– My media settings allow auto embeds.
– WordPress was updated lastweek
– I removed the wpautop() filter – it didn’t do anything so I reset it.

The code is sitting in a template page, not in a loop.

Any thoughts or help on this would be incredible šŸ™‚

Thanks in advance,

Kyle

An excellent instruction for how to embed YouTube videos directly into a WordPress site. I will try this. Thanks, from Tumbleweed Marketing Analytics.

I got it to work with Ustream recorded video but for some reason it won’t show up as wide as YouTube will. I think its a limitation from Ustream’s end but not sure.

When will part 2 of this tutorial (for self hosted video) be ready? I could really use it asap šŸ™‚

Actually I’ve worked this out for myself – thanks in part to Steve Heffernan’s great tutorial on html5 video at lynda.com. Also loving your tutorials Morten, they’re a big help – thanks!

I used this in combination with what I learned from the Lynda series on Online Portfolios. I am extremely pleased with the results! You are an excellent teacher.

I altered the code slightly and was able to embed recorded videos from Ustream the same way, I just had to use a different URL and variable.

found the solution for my problem:

changing from ā€œembed_oembed_htmlā€ to ā€œoembed_resultā€ so that it’ll work also with ā€œwp_oembed_get

Hello and thanks for the code. Can you tell me how to add code to make this work for both youtube and vimeo? (Just up to the “Making it conditional” part.

Thanks!

This may be a little off this specific post topic. My question is about using the oembed method. Is there a way to control how the video styling on a site using this method?

So far, I can only find tutorials online that explain how to use parameters ( https://developers.google.com/youtube/player_parameters#showinfo ) by wrapping the link and using the old method of embedding. I love how easy it is for my clients to slap a link in the visual editor; this is fantastic! I just can’t figure out how to make it pretty in the theme display by allowing such customizations as “&showinfo=0”, “&theme=light”, and “&color=white”.

Thanks Morten! Also, thank you for shaping my career with your Lynda videos! You’ve influenced my life in the most positive way!

Hey, thanks for this. Can you tell me the code I’d need to add to change the size of the player to be 600 pixels wide?

Thanks again for the great tutorial.

Hey, thanks for this. Can you tell me the code I’d need to add to change the size of the player to be 600 pixels wide?

Thanks again for the great tutorial.

This was exactly what I needed!! Thanks! The problem I was having was I am trying to customized my wordpress site. The theme we have has a small post area so when we would add video s using the url straight into the post it would look horrible. The only option was to change the post PHP to place the video exactly where we wanted it. Which was outside the actual text of the post. Brillante, you saved my a lot of headache my friend!!

I’m using this code to adjust the width and height to the embedded video.

ID, ‘video_url’, true);
// Echo the embed code via oEmbed
echo wp_oembed_get( ‘http://www.youtube.com/watch?v=’ . $videoID , array(‘width’=>300,’height’=>300) );
?>

Hi, it seems like something in the way your site displays code got messed up for this post. Could you please fix it? I’m trying it out in a project I’m working on.

Mr. Morten Acutely Ur Amazing , I following your WordPress course in Lynda Online .
You always surprise me with you Genius Mind & Idea šŸ˜€

This code currently does not work, because a day or two days ago youtube ads a ) at the end of the link. How can we solve this problem? Thanks in advance.

It works again. Youtube as already correct the ) that appeared at the end of the iframe code. Thanks. Nice website and tutorials by the way.

the only thing that would be great to know is how and where should we put the ?rel=0 or ?autoplay=1. those kind of attributes. That would be great.

forget it. i’ve already figured it out.

echo wp_oembed_get( $videoID, array( ‘rel’ => 0) );

just add this to function.php

add_filter(‘oembed_result’,’lc_oembed_result’, 10, 3);
function lc_oembed_result($html, $url, $args) {

// $args includes custom argument

$newargs = $args;
// get rid of discover=true argument
array_pop( $newargs );

$parameters = http_build_query( $newargs );

// Modify video parameters
$html = str_replace( ‘?feature=oembed’, ‘?feature=oembed’.’&’.$parameters, $html );

return $html;
}

It worked for me. That should work also for the user Brooke. Thanks.

Thanks a lot for this short tutorial, exactly what I was looking for. Worked like charm šŸ™‚

How can we do the same, but this time to display a map from google maps? Thanks in advance.

Great tutorial.

My problem is that I want to embed two YouTube videos into my site footer.php, and I want these YouTube links to be editable in the admin area somewhere (maybe two custom fields).

How would I go about achieving this?

Thanks.

Thanks for this nice trick.
Can you help me about this: ?
my website is about movies.
I want to use custom fields to put a button in posts single page that a user click on it to show movie trailer in a popup fancy box.the trailers links loads from youtube.
but if there is no trailer link, the button disappear too.
What am I spouse to do?
thanks again.

This is great and I have got this working in my page template. I was wondering if it’s possible to use this in a widget? I want to have the same sidebar on all my artist pages, but the youtube video to change for each page by using that pages video_URL custom field. I have tried PHP Code Widget plugin and using the same code in text widget, but this doesn’t work..

Id like to add that if you put the above code in and your video does not show up. Simply take out the Youtube URL in bracket after wp_embed_get, Make sure you leave the quotes.

ID, ‘video_url’, true);
echo wp_oembed_get( ” . $videoID );
?>

The code is basically saying to embed anything that’s in the video_url custom field. It should also embed your vimeo videos too. Worked like a charm for me.

The original code for some reason did not work, possibly because of the theme I’m using. Once I made that minor change (after hours of pulling my hair out trying to figure it out lol) it finally worked.

I hope this helps. And thanks for the awesome post/tips

Comments are closed.