Deluxe Blog Tips About Projects

How To Show Youtube Video Outside The Post In WordPress

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.

Subscribe to the Newsletter

Subscribe to get my latest content by email. I won't send you spam. Unsubscribe at any time.