12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Mar 24, 2019

Displaying YouTube video from a custom field conditionally in Oxygen

Sridhar Katakam

In Oxygen's Facebook group a user asks:

I have a field where I enter a YouTube URL, and a template where I get that dynamic field. If the field is empty the template will render that iframe with an empty value, si I have a huge white space on the front-end.

to which I replied:

You could add a custom shortcode that returns the enclosed content if the field has a value and use it in a Shortcode Wrapper element.

In this members-only tutorial, we shall

  • attach a field group having a YouTube Video URL Url type custom field using Advanced Custom Fields to single posts.
  • register a custom shortcode that shows the content if a YouTube URL has been set for single posts.
  • use Oxygen's Shortcode Wrapper component with the above shortcode.
  • add a Code Block inside the Shortcode Wrapper to extract the ID from the YouTube video URL and pass it on to iframe embed code.
  • add CSS to make the video take up the full available width while maintaining the height per the video's aspect ratio.

We are going to ensure that no space gets taken up on the front end if a post does not have a YouTube URL set.


In the post editor screen
In the front end

Step 1

Install and activate ACF.

Go to Custom Fields > Add New.

Title: Post Meta

Add a new "YouTube Video URL" field that is of Url type.

In the Location section, Set the field group to appear on your desired post type (Post, in this case).

Step 2

Install and activate Code Snippets plugin.

Go to Snippets > Add New.

Title: Shortcode to display the content if YouTube URL has been set for single posts


This is a premium members-only content.

To view the rest of the content, please sign up for membership ($47/month or $599 one-time).

Already a member? Log in below or here.