10

WordPress automatically embeds a youtube video's if I use:

[embed] http://www.youtube.com/watch?v=Xog1T5dUxcw [/embed ]

This is great, but it doesn't work if I use it in a template file. I have a custom field where the admin can put a URL to a YouTube video. I want to get the video in the single-post using the following code:

<?php
  $custom = get_post_custom($post->ID);
  $url = $custom['_videoLink'][0];
?>
<div class="video">
  [embed]<?php $url; ?>[/embed]
</div>

How can I convert the Youtube URL into an embed URL using the standard WordPress [embed] function?

2 Answers 2

17

Use wp_oembed_get( $url ) instead. Make sure you echo it in your template file. So, something like this:

<?php
// tot necessary to set this but good if $url is coming from a function
$url = 'https://www.youtube.com/watch?v=jofNR_WkoCE';

// echo the function in your template to render the video
echo wp_oembed_get( $url );
?>
1
  • Easy and best solution for this problem. +1
    – Sam
    Sep 3, 2014 at 8:04
10

Normally you have to use do_shortcode in a template to place a shortcode outside of the content, however, I've had trouble with the embed shortcode specifically and could not make it work that way. I found this solution which works, but maybe there's a way to do this with do_shortcode and I've missed something.

<?php
$custom = get_post_custom($post->ID);
$url = $custom['_videoLink'][0];
if($url):
    $shortcode = '[embed]'.$url.'[/embed]';
    global $wp_embed;
    echo $wp_embed->run_shortcode($shortcode);
endif;
?>
3
  • You can do also echo do_shortcode($shortcode)
    – keatch
    Jan 30, 2012 at 8:20
  • @keatch - have you tried this specifically with WP's embed shortcode? as I mentioned, that specific one would not work for me, whereas other short codes normally do. I haven't done much investigation as to why. This was also not with the most recent WP version.
    – Milo
    Jan 30, 2012 at 15:20
  • 1
    I know this is old, but just to point out I'm still having the same issue now in 2013 with the embed shortcode not working in template files. The above solution worked great though.
    – Eckstein
    Aug 15, 2013 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.