How To Show Youtube Video Outside The Post In WordPress

embed youtube video

embed youtube videoEmbedding Youtube video in the post content in WordPress is extremely easy, just wrap it in the [ embed ]. Or even easier by checking the options Auto-embeds in Settings > Media and WordPress will automatically turns Youtube URL into the embedded video.

But that’s for the post content. How do we embed the Youtube video in other places of WordPress blog, such as sidebar, footer, etc.? Especially when you add the Youtube URL to the post using custom meta field?

The first idea shown in my mind is that apply the shortcode [ embed ], just like this:

$video_url = get_post_meta( get_the_ID(), 'youtube', true );
echo do_shortcode( "[ embed ]{$video_url}[ /embed ]" );

But it doesn’t work! Actually, the [ embed ] shortcode is not a real shortcode, meaning it’s not available site-wide. It’s added only when WordPress processes the post content, thus available only inside the loop.

So, to solve this problem, we need to use a function wp_oembed_get():

$video_url = get_post_meta( get_the_ID(), 'youtube', true );
echo wp_oembed_get( $video_url, array( 'width' => 400 ) );

The 1st argument is the Youtube video URL, or even better, any supported oEmbed services. The 2nd argument is an array of video arguments such as width, height.

Hope that’s helpful for you.

7 thoughts on “How To Show Youtube Video Outside The Post In WordPress

  1. Note that the reason that embed shortcode is special case is that it doesn’t merely do real time processing, it also caches results in custom field and should happen in context of specific post.

    Without that (or other form of caching) you would be hitting remote site every time with HTTP request, which will completely kill page load performance.

  2. Nice post.. This is the first article I found mentioned about to insert video outside the post in wordpress. I visited many blogs but there were just same technique and title. I appreciate.

Comments are closed.

Newsletter

Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

60% OFF for Meta Box Lifetime Bundle Get It Now