WordPress

WordPress Hacks: Using Custom Fields to Auto-Embed YouTube Videos

[intermediate] If you only use videos once in a while on your WordPress-run site, this hack probably isn’t of much use to you. But if you embed videos regularly, you probably get tired of copying and pasting the embed code all the time. Another possibility is that you want your in-post videos to show only on permalink pages, not on the home page. You can satisfy those and other functionalities by using WordPress custom fields and a little bit of HTML/ WP PHP code to control how and where your video shows up.

Sounds complicated, but if you have even a little bit of experience with coding in WordPress (a combo of HTML and PHP, with WP functions and sometimes JavaScript), then process is relatively simple. I’m assuming below that you have some experience in creating a custom field. (There’s a snapshot below if you haven’t.) Let’s go through the first-time process:

  1. From your WP admin panel, create a new post. Then create a custom field: “youtube_id”. (Once you create the custom field, it will be available to all other posts, old or new.)
  2. Assign to the youtube_id field the id of the youtube video that you want to embed. It’s the value after the “watch?v=” in a YouTube URL. So if the url is http://www.youtube.com/watch?v=pxNGKICfi_g, the youtube video id is “pxNGKICfi_g”. This is the value you’ll enter (without quotations) into the custom field youtube_id.
  3. Save the post.
  4. Insert the custom code block (shown below) in your permalink template. Usually this will be in the single.php template file of your WP theme. Place the code where you need it. I like to place videos at the end of a post, but what you do will depend on your requirements.
  5. Refresh your permalink (post) page and you should see the video embedded.

Those are the steps that you take the first time, for each unique custom field you create. The next time you want to use the same field in another post, you only need to do steps #2, 3 and 5.

The Technical Details

Here are the technical details for this process.

Creating a Custom Fields

Each time you create a custom field in WP, it will be available from other posts. If you’ve never done this before, just view the snapshots below.

Snapshot 1 (above): Create a new post and scroll down in the Write panel to the Custom Fields area. In the middle column, enter the name of the custom field you want to create. (In this case, youtube_id.) Then paste or type the field value for the post you are creating/ editing. (In this case, whatever youtube id you’d like. Remember not to enter the full URL of the video, just the id.)

Snapshot 2 (above): Click the “Add Custom Field” button and you’ll see the field and its value added. This field name will now show up in the custom field drop down menu in the left column.

Custom Fields Code Block

You can create whatever custom fields you want, but without some PHP code to manipulate them, and HTML code to display them, you’ll never see the results of the field values on your web pages. The code you need for the YouTube video embed is relatively simple:


ID, 'youtube_id', true))
  {
    $values = get_post_custom_values("youtube_id");
    $youtube_id = $values[0];

?>


} ?>

The first chunk, in PHP code, checks to see if the current post page has a custom field titled “youtube_id”. If it does, then grab the value of the field, save it into $youtube_id, and substitute it into the HTML code chunk below. There are two places in the HTML chunk where $youtube_id is used. The result when that HTML code is rendered is the proper YouTube embed code.

To use this code in your WP site, copy from above and paste into it your single page template file (usually single.php). The video size is the default YouTube size of 425 px wide x 355 px high. You can change this, of course, simply by adjusting those numbers in the HTML code block (both locations). YouTube will then resize the video upon rendering.

Example

At [email protected], I’ve set up a single page with video embedded. To see a page without video, look at the Leatherheads snapshot below.

Now look at the snapshot of The Ruins page, below, which has a YouTube centered under the poster.

In the case of [email protected], I inserted the code into “the loop” in single.php, just before the ratings stars code. If you download a copy of my single.php, you can see where the code has been placed, just near the top of a loop of code.

Hopefully this is a sufficient example for you to do something similar. Give it a try, and if you still have questions, drop a comment here and I’ll do what I can to answer.

Author: Raj Dash

14 thoughts on “WordPress Hacks: Using Custom Fields to Auto-Embed YouTube Videos

  1. Hi there,

    This code didn’t work for me until I added before the very last line. I.e., the last line of code as it is written above is:

    } ?>

    I had to change it to this:

    I'm just learning PHP so I can't say why this works. I do think I've seen similar PHP code for conditional wordpress statements. Either way, if you are having trouble try this and see if it helps.

    Btw, thanks for this tip. It was EXACTLY what I was looking for. I now have your site on my radar (i.e., Google Reader) for other quality WordPress as CMS tips. Keep them coming.

    Also, one last question -- what if I want to have a default sidebar video that displays if there is no custom value in the post - how would I set that up?

    Be well,

    Moshe

  2. Sorry, my english is not very good, but i make some changes to see the video only on the “extract” of the post. Like in my new blog http://www.geek1983.com

    You need to put this code in the index.php

    ID, ‘dailymotion’, true)){

    $values = get_post_custom_values(“dailymotion”);
    $dailymotion = $values[0];

    echo ‘

    ‘;
    }elseif(get_post_meta($post->ID, ‘youtube’, true)){

    $values = get_post_custom_values(“youtube”);
    $youtube = $values[0];

    echo ‘

    ‘;
    }
    ?>

  3. hey,

    thanks for the post. i have seen your pre, code or blockquote content goes into the sidebar (tested in firefox 3). use this code to fix the problem:

    white-space: pre-wrap; /* css-3 */
    white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */

    Many greetings,
    Sebastian

    http://www.knowtebook.com – Webworker Dailky Milk

  4. Hi Friends,

    I am a beginner and wanted to make use of Youtube feeds. Is it possible to syndicate the youtube video feeds to embed directly into posts (Single Video-single post). Please help me doing this.

    Any soft of help will be really appreciated.

    Thanks,
    Nash

  5. Adam: You’re right. Thanks. I must have pasted that code, then inadvertently removed that extra bracket.

    Miriam: Try what Adam said.

    I’ve made a change to the code block. Next time, I’ll remember to attach a copy of the code in a text file.

  6. Looks like Line 1 of the Custom Fields Code Block could use another closing bracket “)” on the end of the line. With that in place it worked great for me, thanks.

  7. Miriam: I’ll need to know more details. I can have a look at your site sometime this week, if you like. But without knowing how you set up your fields and where you put your code, it’s hard to say. PM me with your email addr. I’ll contact you, and you can then email me a copy of your HTML where the code block has been placed. My suspicion, however, is that maybe a piece of the code is missing? (It doesn’t show well in the code block above.) I should have attached a file as well. I’ll try to do that later today. (You can “remind” me if I forget.)

    Sila: Sure. What you do is reuse the same custom field in a given post. However, you would need to tweak the handler code to expect 1 or more values. For example, after you get $values, you would need to stick in a PHP foreach loop.

  8. this is a good one, thanks!
    what would one do to display more than one video? like having several youtube id’s values?

  9. This method is excellent, and I really want to use it on one of my sites where I want the videos to be smaller on the home page, but regular size on internal pages. I set it up as you suggested here, and it didn’t work. I kept getting error messages. Is it possible that the code above shouldn’t be copied and pasted? Or that it won’t work depending on the loop used in a blog?

    Thanks!

  10. Sam: Absolutely. There are tons of great WP plugins for video. I’m just trying to get more people to use WP Custom Fields using simple examples so that, later, I can write up complex examples without having difficult to follow post. I can just link back to this one, for those who don’t know how to use Custom Fields.

Comments are closed.