How to Enable oEmbed in Text/HTML Widgets in WordPress

WPTurbo » Snippets » How to Enable oEmbed in Text/HTML Widgets in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Do you want to embed rich media content from sites like YouTube, Vimeo, or Twitter into your Text/HTML widgets in WordPress? By default, WordPress does not support oEmbeds in Text/HTML widgets. However, with a few simple steps, you can enable oEmbeds and effortlessly embed media content in your Text/HTML widgets. In this article, we will guide you through the process of enabling oEmbeds in Text/HTML widgets in WordPress.

					function wpturbo_enable_oembed_in_texthtml_widgets( $text ) {
    global $wp_embed;
    if ( 'post_widget_text' === $GLOBALS['current_screen']->id ) {
        $text = $wp_embed->autoembed( $text );
    }
    return $text;
}
add_filter( 'widget_text_content', 'wpturbo_enable_oembed_in_texthtml_widgets' );
				

The code snippet provided enables oEmbed functionality within Text/HTML widgets in WordPress. By default, oEmbed is not supported in Text/HTML widgets, but with this code, we can enable it.

The first step is to define a function called wpturbo_enable_oembed_in_texthtml_widgets(). This function takes one parameter, $text, which represents the content of the widget.

Next, we use the global $wp_embed; statement to make the $wp_embed object available inside the function. The $wp_embed object is responsible for handling oEmbed functionality in WordPress.

We then check if the current screen is the Text/HTML widget screen by using the condition 'post_widget_text' === $GLOBALS['current_screen']->id. If it is, we proceed to the next step.

Inside the condition, we use the $wp_embed->autoembed() function to autoembed oEmbed content in the $text variable. This function automatically detects URLs in the content and replaces them with embedded content, such as videos, tweets, or other media.

Finally, we return the modified $text variable to ensure that the oEmbed functionality is applied to the Text/HTML widget content.

To implement this feature, we need to add the wpturbo_enable_oembed_in_texthtml_widgets() function to the widget_text_content filter using the add_filter() function. This filter allows us to modify the content of Text/HTML widgets before it is displayed on the front-end.

By adding the line add_filter( 'widget_text_content', 'wpturbo_enable_oembed_in_texthtml_widgets' );, we are hooking our function into the filter and ensuring that oEmbed is enabled for Text/HTML widgets.

Now, when a Text/HTML widget contains a URL to a supported oEmbed provider (e.g., YouTube, Twitter, Vimeo), the embedded content will be automatically displayed on the front-end of the website.

Register an account to save your snippets or go Pro to get more features.