How to show Youtube video outside post content in WordPress

Embedding Youtube video in the post content in WordPress is extremely easy, just wrap it in the embed shortcode. 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 fields?

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, [ '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.

We're using this technique to render oEmbed field in Meta Box on the front end. It's easy, stable and reliable.

If you're struggling with outputting an Youtube video outside of the post content, I hope this code will help you. If you like this post, please share it with your friends.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Leave a Reply

Your email address will not be published. Required fields are marked *


Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO