Simple video embedding with custom fields in WordPress – YouTube

By Morten Rand-Hendriksen on
Creating a custom video field in WordPress

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.

11 comments

  1. 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

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">