Simple video embedding with custom fields in WordPress – YouTube

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.

Comments

46 responses to “Simple video embedding with custom fields in WordPress – YouTube”

  1. David Paulsson Avatar

    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.

    1. Morten Rand-Hendriksen Avatar

      The point of this tutorial is to pull the video out of the_content() and place it somewhere else on the page. Example: http://www.idearefinery.net/tutorials/live-trace-effect-in-illustrator/

      1. Usemeplz Avatar

        A good example, thank you.

  2. Carl Papworth Avatar

    Is it possible to use multiple custom fields in the same post, and in this way publish multiple videos in this one post?

  3. Carl Papworth Avatar

    Is it possible to ad multiple custom fields (with same tag) and generate multiple videos in one post?

  4. Kyle Avatar
    Kyle

    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

  5. Tumbleweed Analytics Avatar
    Tumbleweed Analytics

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

  6. wordpress Avatar
    wordpress

    hi,
    how r u sir??? i like ur every tutorial very much,,,, u r grt!!!!

    1. Raees Avatar
      Raees

      Thanks sir nice tutorial with the help of example

  7. Usemeplz Avatar

    And besides YouTube, is it possible to embed videos from other video hosting sites?

    1. Eric Avatar
      Eric

      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.

  8. Mrgarethnunn Avatar
    Mrgarethnunn

    Superp, really appreciate your blog, great post. Helped me out tremendoulsy

  9. euro trading Avatar

    Thanks for sharing such an interesting information

  10. Grant Avatar
    Grant

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

    1. Grant Avatar
      Grant

      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!

  11. Shavindra Avatar

    Perfect!!! works like a charm šŸ™‚

  12. qualityhoustonroofing.com Avatar

    Hi, yup this article is genuinely fastidious and I have learned lot of things from it on
    the topic of blogging. thanks.

  13. Eric Avatar
    Eric

    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.

  14. Brian Olson Avatar
    Brian Olson

    Thanks, this worked great… is there a way to get it to autoplay?

    Thanks!

  15. Sadaf Chohan Avatar
    Sadaf Chohan

    Fantastic wot a helping tutorial

  16. Erwin Avatar

    Hi mate – any idea to get the ‘oEmbed Transparency add filter’ working for this? (http://www.wpbeginner.com/wp-tutorials/how-to-prevent-youtube-oembed-from-overriding-your-wordpress-content/).
    Having this on the embeds via the content area works fine but not with the custom fields.

    1. Erwin Avatar

      found the solution for my problem:

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

  17. get rid virus.java.agent easily Avatar

    Pretty! This has been a really wonderful post. Thanks for supplying these details.

  18. Doug Avatar

    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!

  19. Brooke Avatar
    Brooke

    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!

  20. Doug Avatar

    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.

  21. isabella Avatar
    isabella

    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.

  22. Joshua Rivera Avatar

    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!!

    1. Tommy Avatar
      Tommy

      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) );
      ?>

  23. Gustavo Avatar

    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.

    1. Morten Rand-Hendriksen Avatar

      Sorry, I just changed the code display plugin and my older posts have not been updated. I’ve fixed it.

  24. Ehab Avatar

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

  25. João Avatar
    João

    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.

    1. Morten Rand-Hendriksen Avatar

      I have to look into it.

  26. João Avatar
    João

    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.

  27. João Avatar
    João

    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.

  28. João Avatar
    João

    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.

  29. Pranjal Avatar
    Pranjal

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

  30. João Avatar
    João

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

  31. Danny Avatar

    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.

  32. Amit Avatar

    Can we do the same for the Google Maps too.

    I need a template having a youtube video and the google map both

    Thanks in advance

  33. Brad Dalton Avatar

    I use this http://img.youtube.com/vi/ to grab the thumbnail.

  34. Mike Avatar
    Mike

    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.

  35. Lizzy Avatar
    Lizzy

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

  36. Al Cayne Avatar

    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