WordPress
Article

The Complete Guide to Using WordPress Embeds

By David Attard

When you’re writing frequent posts on your WordPress website, you know that many times you’ll need to embed external content.

Whether that is a video from YouTube or Vimeo, a music clip from SoundCloud or Spotify, a Tweet or a Vine, a Flickr on an Instagram, there is not much to be done. You simply copy and paste the URL you want to embed into your WordPress article and that’s it.

This article will go through all of the details related to the WordPress embed and oEmbed functionality.

Why Does WordPress Need an Embed Feature?

One of the things which WordPress does really nicely when compared to other CMS’ I’ve used, is its ease to embed external media.

Without mentioning any names, embedding a simple a YouTube video into an article using one of the most popular CMS’s out there (other than WordPress) can be a nightmare of epic proportions.

Side note: this is a plea, not a dig. Embedding a YouTube video into an article should be a breeze in any CMS.

Why does this happen?

In reality, embedding external content is typically a potential security issue. Content is typically embedded using iFrames. An iFrame is simply a new “window” which is allowed to reference any external functionality.

If you want to embed a video from YouTube for example, you would need to embed the following syntax:

<iframe width="560" height="315" src="https://www.youtube.com/embed/aDorTBEhEtk" frameborder="0" allowfullscreen></iframe>

So what’s the problem with that?

Nothing is actually wrong with this specific code. However, allowing anybody to enter iFrames into your posts is a serious security risk.

Why is it a security risk you may ask?

Whilst embedding a YouTube iFrame is fine, an iFrame can be used to reference ANY site. Users with malicious intent may actually embed an iFrame which references a site which is hosting malware.

To top it all off, iFrames can be hidden as 0 x 0 size pixel (an invisible dot), which makes it very hard to detect, at least with the naked eye.

Hence, why iFrames are discouraged in areas where user input is allowed.

In other CMS’, where the type of embed supported by WordPress is enabled, you can embed external media by doing one of the following:

  1. Use a third party plugin
  2. Allow embedding of iFrames (thus creating a potential security risk)

In fact, even using the WordPress embed function, only certain third party services are allowed. There’s an internal whitelist which determines which services are allowed and which ones aren’t. This is to mitigate any potential security issues.

How Does the WordPress Embed Feature Work?

There are a number of services which are supported by the WordPress Embed feature. You can find a full listing of services supported by Embed here.

The WordPress embed feature works by implementing the oEmbed API – essentially this is a way in which a consumer website (such as WordPress) can display embedded content from a provider (such as YouTube).

The consumer sends a HTTP request to the provider, and the provider replies with a JSON or XML HTTP response with the data structured in such a way as to allow the embedding of that media into the consumer website.

This is the request:

http://www.youtube.com/oembed?url=http%3A//youtube.com/watch%3Fv%3DM3r2XDceM6A&format=json

And this is the response:

{"html": "\u003ciframe width=\"480\" height=\"270\" src=\"https:\/\/www.youtube.com\/embed\/M3r2XDceM6A?feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e", "thumbnail_height": 360, 
"thumbnail_width": 480, 
"title": "Amazing Nintendo Facts", 
"width": 480, 
"height": 270, 
"type": "video", 
"provider_url": "https:\/\/www.youtube.com\/", 
"thumbnail_url": "https:\/\/i.ytimg.com\/vi\/M3r2XDceM6A\/hqdefault.jpg", 
"author_name": "ZackScott", "
author_url": "https:\/\/www.youtube.com\/user\/ZackScott", "version": "1.0", 
"provider_name": "YouTube"}

This is of course something which happens behind the scenes.

Embedding Media into WordPress

Now that we understand the functions behind WordPress, let’s see a few examples of media which can be embedded into a WordPress post.

You’ve probably done this already: embedding a YouTube video.

Rather than having to use the normal syntax associated with embedding a YouTube video, which is something similar to the following:

<iframe width="560" height="315" src="https://www.youtube.com/embed/O_Bw1_0u1P8" frameborder="0" allowfullscreen></iframe>

You simple take the YouTube video URL and paste it into your post:

https://www.youtube.com/watch?v=O_Bw1_0u1P8

WordPress embed YouTube video

That’s it.

Just make sure it’s not actually converted into a hyperlink.

You are now able to see a preview of the video in the editor.

Once your post goes live, you’ll see the YouTube embedded in your post.

Next, let’s embed a Tweet into our post. Find the tweet you want to embed, click on the ellipses to get the link and then just post that into your WordPress post.

WordPress embed link to Tweet

https://twitter.com/sitepointdotcom/status/756595431182835713

The result will look something like this:

WordPress embed Twitter

This all happens automatically without needing to mess around with tags and blockquotes and iFrames and whatever else.

Let’s embed a SoundCloud file into our post. Once again, it’s just a question of finding the URL of the file you want to embed and pasting it into post.

https://soundcloud.com/versioningshow/ver002-mat-marquis-on-the-versionong-show

You can see from the screenshot below, as soon as we entered the URL into the post, we immediately get a preview of the file which is going to be embedded into the post.

Embed SoundCloud WordPress

We could keep showing various other examples, but we’re sure you got the point.

Styling: Setting the (Maximum) Size of Embedded Media

In theory there is not much need for styling. The WordPress oEmbed feature is able to cater for most of the styling. It also handles responsiveness of your theme, so you don’t need to really worry about that either.

In practice though, there might be some need for you to actually size the media you are embedding.

The WordPress oEmbed functionality is in reality being handled by the [Embed] shortcode .

Using the [Embed] shortcode, you can set the maximum dimensions that a piece of media can take. These are not fixed, because of course we want the post to remain responsive.

[embed width="560" height="315"]https://www.youtube.com/watch?v=O_Bw1_0u1P8[/embed]

Enable Media from Other Sites to Be Embedded

We mentioned a few paragraphs up that WordPress does not allow embedding of media from any site for security reasons.

However, if you want to embed media from a website which is not supported, you can of course do that.

To do this, you’ll need to add the site to the internal whitelist.

There are two ways of doing this, the method which you should use depends on whether the site supports the oEmbed API or not.

Adding Sites Which Support oEmbed API

In the functions.php file of your theme or plugin where you want to allow the embedding, call the following function to add a new site to the embed provider whitelist.

wp_oembed_add_provider

<?php wp_oembed_add_provider( $format, $provider, $regex ); ?>

For example,

<?php wp_oembed_add_provider( 'http://example.com/watchvideo/*', 'http://example.com/oembedprovider' ); ?>

If the media can be embedded via various URLs, you can use a Regular Expression to describe the various URLs possible. If we wanted to add our fictioutious site, TheNewTube with a regular expression, we could use the following:

<?php wp_oembed_add_provider( '#http://(www\.)?thenewtube\.com/watch.*#i', 'http://www.thenewtube.com/oembed', true ); ?>

Adding Sites Which Don’t Support oEmbed API

If the site you want to embed does not support oEmbed, you can still add them as a provider.

Again, through the functions.php file, you need to register the site using the wp_embed_register_handler

<?php wp_embed_register_handler( $id, $regex, $callback, $priority ); ?>

You’ll also need to provide a callback function, that would be used to generate the HTML required to embed the media.

The WordPress codex provides an example of how to do this to embed video from the Forbes website:

<?php

wp_embed_register_handler( 'forbes', '#http://(?:www|video)\.forbes\.com/(?:video/embed/embed\.html|embedvideo/)\?show=([\d]+)&format=frame&height=([\d]+)&width=([\d]+)&video=(.+?)($|&)#i', 'wp_embed_handler_forbes' );

function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr ) {

    $embed = sprintf(
            '<iframe src="http://www.forbes.com/video/embed/embed.html?show=%1$s&format=frame&height=%2$s&width=%3$s&video=%4$s&mode=render" width="%3$spx" height="%2$spx" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>',
            esc_attr($matches[1]),
            esc_attr($matches[2]),
            esc_attr($matches[3]),
            esc_attr($matches[4])
            );

    return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );
}

?>

If you need to do this for your site, it would be best to consult and hire a WordPress developer, just to make sure you don’t introduce any bugs which could break your site.

WordPress as an oEmbed Provider (Since WordPress Version 4.4)

Up till now we were only discussing WordPress as being a consumer of media from 3rd party sites, in reality WordPress was the oEmbed consumer.

WordPress as oEmbed Provider

Since 4.4, WordPress can also act as a Provider of oEmbed content.

What this means is that any public posts, or post types on your site can be embedded into third party websites via your own WordPress website (typically via their pretty permanent URL with an embed added to the end of the actual URL – example.com/your-post/embed/).

For security reasons, embeds reside in a sandboxed iFrame, however the content of the iFrame is a template that can be styled or replaced entirely by the theme on the provider site.

Functions and Hooks for Using Embeds

Here are the four most useful functions related to embeds:

Customizing the oEmbed Output

Similar to customizing any template file, the embed template from a post can be styled using embed_head and embed_footer to add custom code to the beginning and end of the embed template.

The X-WP-embed:true header will be also be sent when that template is used. This makes it easier to target embedded posts in any application which is consuming WordPress oEmbeds.

Summary

As we’ve seen in this article, the embed features of WordPress are quite rich in scope. Both for a writer and for a developer, there are plenty of ways in which WordPress embeds can be used to enhance content with embedded media.

Have you used WordPress embedding in any creative ways? We’d love to see and share your examples.

  • coopersita

    The code for “Styling: Setting the (Maximum) Size of Embedded Media” is not showing up.

    • http://chrisburgess.com.au/ Chris Burgess

      Thanks for the heads up, it’s fixed now – much appreciated :)

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Instant Website Review

Use Woorank to analyze and optimize your website to improve your website to improve your ranking!

Run a review to see how your site can improve across 70+ metrics!

Get the latest in WordPress, once a week, for free.