FLASHSALE30 for 30% OFF AVF Pro – Ends in:

0

Days

:

0

Hrs

:

0

Mins

:

0

Secs

Shop now!
WPLake > Learning Hub > ACF oEmbed Field: Complete Guide with Code Snippets
  • Deutsch
  • Español
  • Français
  • Italiano

ACF oEmbed Field: Complete Guide with Code Snippets

Discover how the ACF oEmbed field simplifies embedding media in WordPress, offering previews, customization, and broad content compatibility.
Embed songs or videos from YouTube

Key Points at a Glance

  1. About the ACF oEmbed field: Simplifies embedding third-party media like YouTube and Vimeo videos directly in WordPress content.
  2. Behind the scene: Uses WordPress's built-in oEmbed feature to convert media URLs into iframes automatically.
  3. Compatibility: Supports various content types beyond videos, including Facebook, Instagram, Twitter, and Spotify embeds.
  4. Comparison with direct embedding: Unlike direct iframe embedding, the ACF oEmbed field includes preview features and requires less manual handling.
  5. Customization: Allows modifying the iframe output with PHP or Advanced Views Framework, adding classes, autoplay parameters, or displaying raw URLs.
  6. Alternative field types: Use ACF File or Image fields for selecting files from the Media Library; use the Repeater field to store multiple media elements.

Table of Contents

The ACF oEmbed field, part of the Advanced Custom Fields plugin and categorized under the Content group, simplifies the process of embedding media from third-party sources. With this field type, editors can easily include content like YouTube or Vimeo videos directly in their posts or pages.

This functionality allows you to present external media seamlessly alongside content stored in your Media Library. The field utilizes WordPress’s built-in oEmbed feature, which automatically retrieves the proper embed URL and wraps it in an iframe tag.

Note: The video page URL and the video embed URL serve different purposes. The video page URL displays not only the video but also comments, related videos, and more. For example: https://www.youtube.com/watch?v=7wtfhZwyrcc.
In contrast, the embed URL is a direct link to the video without additional information: https://www.youtube.com/embed/7wtfhZwyrcc?feature=oembed.

When you paste the page URL, the ACF oEmbed field handles this conversion for you, eliminating the need to manually locate and use the embed URL from the video settings.

ACF oEmbed field UI

ACF oEmbed field setup
General settings of the ACF oEmbed field type.
ACF oEmbed field preview
Editors can view a preview of the embedded media. The preview element has the height specified in the field settings.

ACF oEmbed field-related addons

ACF addons can be an important part of the workflow, and there are several addons especially useful for the ACF oEmbed field:

  • ACF Quick Edit Fields enhances the WordPress admin experience by adding Quick Edit functionality to Advanced Custom Fields. This plugin allows you to quickly view and edit ACF field values directly from the list views.
  • ACF Tooltip enhances the user experience by managing lengthy instruction texts in ACF fields. Instead of cluttering the edit screen, this plugin allows you to add tooltips to field labels, keeping the interface clean and space-efficient.
  • WPGraphQL for ACF allows you to expose ACF fields and field groups to GraphQL, enabling seamless querying of ACF data within your GraphQL queries.

oEmbed fields in other meta-field plugins

If you’re exploring alternatives to ACF, consider that the oEmbed field in ACF is comparable to the Meta Box oEmbed field and Pods oEmbed field. For a detailed comparison of these and other meta-field plugins, check out our meta-field plugins comparison to understand the differences between them.

1. Direct iframe embedding vs. ACF oEmbed field

When it comes to embedding media, such as videos, you have a couple of options. Direct iframe embedding involves manually adding an iframe code to your content. If you’re using the Gutenberg editor, you can take advantage of the built-in Gutenberg oEmbed block, which not only simplifies embedding but also includes a preview feature.

The Gutenberg oEmbed block appearance. After pasting, it shows the video preview. (Image from WordPress.org)

However, when you need to add oEmbed content to custom post types (CPT) or other parts of your site, you might consider storing the embed code as HTML directly in postmeta fields. While this approach works, it lacks the preview feature and requires more manual handling.

2. ACF oEmbed field essentials

2.1) Field settings

The oEmbed field includes the standard settings such as name, label, and required status. The primary field-specific setting is the embed size, which specifies the width and height used in the iframe attributes. While these dimensions are set within the field, you can also override them with CSS, such as by using the aspect-ratio property.

ACF oEmbed field setup
General settings of the ACF oEmbed field type.

2.2) Storage format and support field locations

The ACF oEmbed field stores the URL as a string in the database. This stored URL is the original one you entered, not the converted oEmbed URL. The conversion to an oEmbed format occurs dynamically when you retrieve the field value, utilizing WordPress’s oEmbed feature.

ACF oEmbed field saves the origin url in the Database.
ACF oEmbed field saves the origin url in the Database.

Supported field locations

You can use the ACF oEmbed field in various locations, and it consistently stores the original URL regardless of where you apply the field:

  1. Post Objects (Post, Page, Media Attachment, CPT Item, WooCommerce Product):
    All content types, including posts, pages, media attachments, and custom post types, are stored in the wp_posts table. The oEmbed URL from the ACF oEmbed field is stored in the wp_postmeta table, associated with the relevant post or custom post type item.
  2. Options Page:
    The oEmbed field can be used on an ACF Options Page, storing the URL in the wp_options table. This makes the oEmbed URL accessible as a global site-wide setting.
  3. User Profiles:
    When the oEmbed field is added to user profiles, the selected URL is stored in the wp_usermeta table, linked to the corresponding user.
  4. Terms (e.g., Post Categories):
    The oEmbed field can be attached to terms, such as post categories, tags, or custom taxonomies. In this case, the URL is stored in the wp_termmeta table, connected to the specific term.
  5. ACF Gutenberg Block:
    The oEmbed field can be added to custom ACF blocks. When used within an ACF Block, the URL is stored within the post_content as part of the block's JSON data structure in the wp_posts table, making it part of the block's content.

2.3) Return value format

Unlike other ACF field types, the oEmbed field does not have a 'return format' setting. The get_field() function always returns the ready-to-use iframe tag for this field type.

This simplifies the process in most cases, but occasionally you might need to customize the iframe, such as adding specific classes or attributes. In such cases, you can modify the iframe markup directly using PHP’s str_replace() function or retrieve the raw URL using get_post_meta() to build your custom iframe code.

2.4) Alternative field types

The oEmbed field is ideal for embedding third-party media elements. However, if you need to select files from the WordPress Media Library, you should use the ACF File or ACF Image fields instead.

Additionally, the oEmbed field does not support storing multiple items. If you need to save multiple media elements, you can use the ACF Repeater field to wrap the oEmbed field and manage multiple entries.

3. oEmbed-compatible services

The ACF oEmbed field is versatile and can be used to embed a variety of external content types beyond just videos. However, keep in mind that the embed source must be supported by WordPress. Here are some of the most popular supported vendors:

  1. Video: YouTube, TikTok, Vimeo, Dailymotion.
  2. Social Media: Facebook, Instagram, Twitter.
  3. Discussion Platforms: Reddit.
  4. Other Media: Spotify, Imgur.

You can find the full list of supported services on the WordPress oEmbed documentation.

4. ACF oEmbed field support in Themes and Builders

ACF is one of the most popular WordPress plugins, and it's supported by many page builders right out of the box. However, most of these integrations are basic, providing limited control over layout or lacking support for advanced field types like Gallery or Repeater.

To achieve universal compatibility with any theme and page builder while gaining advanced control over your layout, consider using the Advanced Views Framework or custom code snippets as discussed in the following chapter.

Here's a snapshot of the built-in features offered by some of the most popular WordPress themes and page builders for displaying ACF oEmbed fields:

Theme/BuilderACF-related featureACF oEmbed type support
Astra-no
AvadaDynamic Contentno (not declared)
BeaverACF Moduleyes
BricksDynamic datano (not declared)
DiviACF Moduleyes
ElementorDynamic Tagsno (not declared)
GeneratePress-no
Gutenberg-no
KadenceDynamic Contentno (not declared)
OceanWP-no
Visual ComposerDynamic Contentno (not declared)
WPBackery-no

While this list may seem brief, many themes come with their own page builders. Check your theme’s documentation for guidance on displaying ACF oEmbed fields, or refer to the universal methods outlined below for a more flexible approach.

5. Code snippets for the ACF oEmbed field

ACF functions and their responses are essentially wrappers around built-in WordPress features. This means that to load and display field values, you need to be familiar not only with ACF but also with core WordPress classes and functions. Additionally, writing markup from scratch and manually escaping data can be time-consuming.

To streamline development, you can use the Advanced Views Framework. This WordPress framework offers smart templates for the front end, simplifying post queries and template creation. It generates default markup and automatically loads the escaped data into the template, allowing you to focus on the layout itself.

Unlike drag-and-drop page builders, smart templates in Advanced Views are modular and based on a template engine (Twig or Blade), providing full control over the markup and helping you avoid the pitfalls of global CSS and JavaScript files. The framework natively supports all ACF field types, along with other data sources.

Below are examples for both Advanced Views and custom code:

5.1) Loading and displaying iframe

To display the oEmbed field, you need to convert the chosen URL into an embed URL (direct source) and then place it within an iframe tag.

An example of the oEmbed YouTube video
An example of the oEmbed YouTube video.

Using Advanced Views Framework

After installing AVF, create a View and choose the target oEmbed field in the Fields tab, then press Publish. The framework will generate the default template, convert the field value, and load it automatically, like this:

{% if oembed.value %}
  <div>
    {{ oembed.value|raw }}
  </div>
{% endif %}

You can now paste the generated shortcode or create a Gutenberg block to display the oEmbed field in the appropriate location. To style the output, add CSS rules to the CSS field of the current View. Advanced Views will automatically enqueue these styles on the target pages.

Loading from different locations: To load a field from different locations (e.g., user profile), use the object-id shortcode argument.

Using custom code

To load the value you should use the ACF get_field() function. Besides specifying the field name, you need to define the source from which to load the field in the get_field() function.

Keep in mind that the response will be an HTML iframe tag, as we mentioned earlier, so you should not escape the output as you usually would with other types of content.

// Use your field name instead of 'oembed'
$oembedHtml = get_field('oembed'); // from the current post
$oembedHtml = get_field('oembed', 10); // from a specific post by ID
$oembedHtml = get_field('oembed', 'option'); // from the options page
$oembedHtml = get_field('oembed', 'user_1'); // from the user by ID
$oembedHtml = get_field('oembed', 'category_2'); // from the category term with ID 2
$oembedHtml = get_field('oembed', 'genre_3'); // from the custom genre term with ID 3

if ($oembedHtml) {
    printf('<div class="embed-container">%s</div>', $oembedHtml);
}

After adding the code to the target template, you can style it by adding CSS rules to your theme's style.css file. However, keep in mind that these styles will be applied sitewide. For more targeted styling, it’s better to add the CSS to a template-specific stylesheet (if your theme supports this) or use the modular Advanced View Framework.

5.2) Adding custom class to iframe

In some cases, you may need to add a custom class directly to the iframe. You can do so by using the replace function.

Using Advanced Views Framework

We can employ the Twig replace filter, as shown below:

{% if oembed.value %}
  <div>
    {{ oembed.value|replace('<iframe ','<iframe class="my-class" ')|raw }}
  </div>
{% endif %}

Now you can add CSS rules for this class to the CSS code field of the current View.

Using custom code

We can employ the str_replace PHP function:

// Use your field name instead of 'oembed'
$oembedHtml = get_field('oembed'); // from the current post

if ($oembedHtml) {
    // Add a custom class to the iframe tag
    $oembedHtml = str_replace('<iframe', '<iframe class="my-class"', $oembedHtml);
    printf('<div class="embed-container">%s</div>', $oembedHtml);
}

Now you can add CSS rules for this class to your theme.

5.3) Enabling video autoplay

If you’ve embedded a video, you can set it to autoplay as soon as visitors open the page, eliminating the need for them to click play. To achieve this, simply add the autoplay parameter to the iframe’s src URL.

Note: The parameter name varies by platform, but for YouTube, use autoplay=1. Also, keep in mind that browsers may block autoplay on certain websites, such as by default on all HTTP sites like localhost. If this happens, check the site’s permissions settings and ensure autoplay is allowed.

Using Advanced Views Framework

Open the View with the oembed field, and inject the autoplay argument using the Twig replace filter, as shown in the AVF oEmbed Docs:

<div class="embed-container">
{{ oembed.value|replace({'" frameborder':'&autoplay=1" frameborder'})|raw }}
</div>

Using custom code

// Use your field name instead of 'oembed'
$oembedHtml = get_field('oembed'); // from the current post

if ($oembedHtml) {
    // Add a custom class to the iframe tag
    $oembedHtml = str_replace('" frameborder', '&autoplay=1" frameborder', $oembedHtml);
    printf('<div class="embed-container">%s</div>', $oembedHtml);
}

5.4) Displaying origin link (like read more)

Displaying media as an embedded iframe is typically what we need in most cases. However, this approach doesn't allow for creating features like "read more" links or any other custom media links. To achieve this, you can work with the 'raw' original URL value, which is not converted into an embed and not wrapped in an iframe.

Tip: while the link title can be hardcoded, it's better to add a separate ACF text field, which editors will use to control it.

Using Advanced Views Framework

For this goal, we can use the raw_value property, loaded automatically by AVF, as shown in the AVF oEmbed Docs:

<div>{{ my_oembed.value|raw }}</div>
<a href="{{ my_oembed.raw_value }}">Watch video</a>

Using custom code

Here, we need to call the get_field() function twice with different arguments. In the first (default) call, you'll get the iframe. In the second call, we'll disable the formatting option of get_field() to retrieve the raw value, like so:

// Use your field name instead of 'oembed'
$oembedHtml = get_field('oembed'); // Get the iframe from the current post

// Get the raw, unformatted value of the oEmbed field
$oembedOriginal = get_field('oembed', false, false); // Disable formatting to get the original URL

if ($oembedHtml) {
    // Display the iframe
    printf('<div class="embed-container">%s</div>', $oembedHtml);
    
    // Display a 'Read More' link using the raw URL
        printf('<a href="%s" target="_blank">Watch video</a>', esc_url($oembedOriginal));
}

5.5) Updating the oEmbed field programmatically

To update the oEmbed field programmatically, you can use the ACF update_field function. Since this field stores the origin URL as a string, the data you pass must be a valid URL.

add_action( 'acf/init', function () {
	// Replace 'my_oembed_field' with your field name, url with the target url,
	// and 1 with the target post ID
	update_field( 'my_oembed_field',
		'https://www.youtube.com/watch?v=7wtfhZwyrcc',
		1
	);
} );

If you need to update the oEmbed field on a user or term object, you must add the appropriate prefix, just as shown in the "loading" field value section.

Note: You should call the update_field function inside the acf/init action, or in any hooks that happen later.

6. Querying by the ACF oEmbed field

As mentioned earlier, the ACF oEmbed field stores the original URL as a string in the database. This means you can query all posts or pages that have a specific value selected. For example, you can find all custom post type (CPT) items that embed a specific video, or even perform a search by domain to locate every item that includes any YouTube video.

However, the approach will differ depending on where the oEmbed field is attached:

6.1) By postmeta (Post, Page, Any CPT)

Using Advanced Views Framework

If you're using the AVF: Pro edition, querying by ACF oEmbed field values is straightforward with Meta Queries. You need to create a Card, choose the target oEmbed field in the Meta Fields tab, and define the desired value. This value can be a static URL or a pointer to another field. The framework will handle the rest.

Using WP_Query

For custom queries, you can use the built-in WP_Query class:

$args = array(
    'post_type' => 'post', // or your CPT
    'post_status' => 'publish',
    'posts_per_page' => -1, // means unlimited
    'meta_query' => array(
        array(
            'key'   => 'your_oembed_field',
            'value' => 'https://example.com/video-url', // target URL
            'compare' => '=' // use LIKE for domain-based searches
        )
    )
);
$query = new WP_Query($args);
foreach($query->get_posts() as $post){
    // Process each WP_Post object
    // Example: echo $post->post_title;
}

6.2) By termmeta (Terms)

Here we need to employ the WP_Term_Query class:

$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        array(
            'key'     => 'your_oembed_field',
            'value'   => 'https://example.com/video-url', // target URL
            'compare' => '=' // use LIKE for domain-based searches
        )
    )
);

$term_query = new WP_Term_Query($args);

foreach ($term_query->get_terms() as $term) {
    // Process each WP_Term object
    // Example: echo $term->name;
}

6.3) By usermeta (user profile)

In this case, we need to use the WP_User_Query class:

$args = array(
    'meta_key'     => 'your_oembed_field',
    'meta_value'   => 'https://example.com/video-url', // target URL
    'compare'      => '=' // use LIKE for domain-based searches
);
$user_query = new WP_User_Query($args);

foreach ($user_query->get_results() as $user) {
    // Process each WP_User object
    // Example: echo $user->user_login;
}

6.4) Inside ACF Blocks

ACF Blocks save their data as JSON in the post_content. This data cannot be queried directly. However, if you enable the "Save in Meta" feature for ACF Blocks, the field values are also saved in post meta, allowing you to query them similarly to other postmeta fields.

7. Related oEmbed field filters and hooks

ACF offers a variety of filters and hooks that enable you to modify field data and behavior, extending WordPress's core hooks functionality. You can utilize the standard add_action and add_filter functions to attach custom code to these hooks.

Below are some of the most commonly used hooks along with the ACF oEmbed field type:

7.1) acf/load_field

The acf/load_field filter allows you to modify the field settings before it is displayed on the editor's screen. This filter is particularly useful for dynamically adjusting the field's configuration, such as setting default values, changing labels, or customizing available options.

add_filter('acf/load_field/name=my_oembed_field', function (array $field): array {
    // Modify the field settings as needed
    $field['instructions'] = 'Please enter a valid oEmbed URL.';

    return $field;
});

7.2) acf/render_field

The acf/render_field action allows you to add custom HTML before or after a field's input on the editor's screen in the WordPress admin. This can be particularly useful for adding custom-styled text, icons, styles, or additional interactive elements to enhance the field's functionality.

add_action('acf/render_field/key=field_123456789abc', function (array $field): void {
    // Your custom HTML
    echo '<div class="my-custom-class">Custom oEmbed-related element</div>';
});

Note: By default, the acf/render_field action is triggered after the field input has been printed. If you need to print your HTML before the input, you should set the priority number to 9 or lower in the third argument of the add_action WordPress function.

7.3) acf/validate_value

Use the acf/validate_value filter to validate the values entered into the field. You can ensure that the entered value meets specific criteria:

add_filter('acf/validate_value/name=my_oembed_field', function($valid, $value, array $field) {
    if (true !== $valid) {
        return $valid; // Skip validation if there is an existing error
    }

    // Custom validation: Ensure the oEmbed URL is a YouTube URL
    $parsed_url = parse_url($value);
    $host = $parsed_url['host'] ?? '';

    if (!in_array($host, ['www.youtube.com', 'youtube.com', 'youtu.be'], true)) {
        $valid = 'Please provide a valid YouTube URL.';
    }

    return $valid;
}, 10, 3);

7.4) acf/validate_save_post

The acf/validate_save_post action allows you to perform custom form validations before saving ACF fields. This is particularly useful when you need to validate one field's value based on another field's input or enforce specific rules across multiple fields.

add_action('acf/validate_save_post', function () {
    // Get the oEmbed field values from ACF fields
    $oembed_1 = $_POST['acf']['field_oembed_id_1'] ?? '';
    $oembed_2 = $_POST['acf']['field_oembed_id_2'] ?? '';

    if (empty($oembed_1) && empty($oembed_2)) {
        acf_add_validation_error('field_oembed_id_1', 'At least one oEmbed field must be defined.');
        acf_add_validation_error('field_oembed_id_2', 'At least one oEmbed field must be defined.');
    }
});

Tip: To find the field key, navigate to the ACF field group in the WordPress admin. Click on the Screen Options button at the top right corner of the page, then check the Field Keys option. Once enabled, the field keys will be displayed next to each field name in the group.

7.5) acf/save_post

The acf/save_post action is triggered when the current item (page/product/user) is saved. You can use it to perform any additional actions, e.g. updating related data.

add_action('acf/save_post', function ($post_id) {
    // Retrieve the oEmbed field value (replace with your actual oEmbed field key)
    $oembed = get_field('project_oembed', $post_id); // Field key for oEmbed

    if (!$oembed) {
        return;
    }

    // Extract the provider name from the oEmbed URL
    $provider = parse_url($oembed, PHP_URL_HOST);

    if (!$provider) {
        return;
    }

    // Update the provider string field with the provider value
    update_field('provider_string', $provider, $post_id); // Replace 'provider_string' with your actual field key for the provider string
});

Stuck with development or facing an issue?

WPLake offers affordable on-demand website development and design.

No matter the size of your project - contact us now, and we'll get it done for you!

Get assistance now

FAQ mode

/

Learning mode

  1. Can I use the ACF oEmbed field for maps embedding?

    No, the ACF oEmbed field isn't suitable for embedding maps. Use ACF Map fields or embed the map directly with HTML code.

  2. Does the ACF oEmbed field support media files from the Media Library?

    No, the ACF oEmbed field is designed for external resources only. For on-site media, use ACF File, Image, or Gallery fields.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

Related articles

Content links (76)

About the Author

Baxter Jones

With over 15 years of experience in the web industry, I specialize in design, user experience, and web best practices. I have a keen eye for detail and thrive on following a structured process in my work. I’m passionate about WordPress, considering it the best innovation since sliced bread. When I’m not at my computer, you’ll find me enjoying time in the garden.

2 Comments

Thomas C
-
25 Mar, 2024
Hi, Good stuff here, very useful thanks! How would you output a Oembed as a link, use case, I'd want to embed my video on a single page template, then just under the embedded content, having a link "view in Youtube". Any suggestions to achieve this?
Reply
Baxter Jones
-
26 Mar, 2024
Admin
Hi Thomas, thank you for your kinds words.
1. The video contains the "Watch on YouTube" link in the bottom left corner by default.
2. By default, ACF returns the iframe markup on get_field call. However, if you pass the third argument (which is responsible for formatting) as false, it will return the raw value, in our case, the link itself. So, you can have two calls in your template: `get_field('name', 1)` and `get_field('name', 1, false)`, and then place them into the appropriate locations.
Reply

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly


    Got it