How to Create a YouTube Embed Plugin for WordPress

Share this article

YouTube is the most popular video sharing platform. As everyone knows, they also lets us embed its videos on our websites. But just taking the embed code and pasting in our site is not enough. It’s not responsive and adds a lot of unnecessary weight to our pages. Due to these issues, users are unlikely to play the videos and we risk them leaving our site.

In this tutorial I’ll show you how to create a YouTube embed plugin which provides a shortcode to add YouTube videos responsively without increasing the weight of the page.

WordPress Default Embeds

WordPress by default, converts YouTube URLs into embed code (using oEmbed) in the post editor.

For example:

Check out this video:

http://www.youtube.com/watch?v=dQw4w9WgXcQ

..is converted to:

Check out this video:

<iframe width="560" height="315" src="http://www.youtube.com/watch?v=dQw4w9WgXcQ" frameborder="0" allowfullscreen></iframe>

WordPress doesn’t apply any other optimization to our video display, such as making it responsive, or dynamically loading the video to decrease page size. With a little work, we can make some significant improvements to the way WordPress handles YouTube videos by default.

How Does YouTube Embed Increase Page Size?

YouTube let’s us embed videos on our website using the standard iframe tag. This embed code downloads ~1MB of resources to just render the video when page loads. And again, ~500KB of extra resources are downloaded when we click the play button to play the video!

This image shows the resources that are downloaded just to render a video:

Default YouTube Page Speed Report

This increases the loading time of your page, thus affecting your ‘pagespeed’ score, which as we know is bad news (further reading here and here).

Responsiveness of YouTube Embedded Videos

The default YouTube embed code is not responsive. The width of the video is 560px and the height is 315px. Therefore, if your website is responsive, then users viewing your website with a screen size less than 560px will likely to have a bad user experience.

Let’s Build Our Plugin!

Let’s create a plugin which tackles these issues. Before we start coding let’s create the plugin directory and its files. Here’s our directory and file structure:

--youtube-embed
    -youtube-embed.php
    -mce.js
    -youtube-embed.js
    -youtube-embed.css

To make the plugin installable, we put the following code in the youtube-embed.php file:

<?php
/**
 * Plugin Name: SitePoint YouTube Embed
 * Plugin URI: https://www.sitepoint.com/
 * Description: An plugin to embed YouTube videos responsively.
 * Version: 1.0
 * Author: Narayan Prusty
 */

Creating the Shortcode

Let’s create a shortcode named youtube which takes a YouTube video ID and generates the HTML code to display the video when viewed on the frontend.

Here’s the code to create the shortcode. Place this code in youtube-embed.php file:

function youtube_embed_callback($atts=null, $content=null)
{
	extract($atts);

	return "<div class='youtube-container-parent'><div class='youtube-container-child'><div class='youtube-video' data-id='". $id ."'></div></div></div>";
}

add_shortcode("youtube", "youtube_embed_callback");

This is how you’ll be able to embed shortcodes in your post editor:

YouTube Default Post Editor

When you view the post you won’t see anything, because instead of returning the iframe embed code, we’re just displaying a div with ID of the video. We’ll dynamically load the embed code only when the user wants to play the video, therefore decreasing the page load time.

Dynamically Loading YouTube Videos

We want to render the video only when a user clicks to play the video. At present, we don’t have any interface to tell the users that a video exists on this page. Therefore, let’s write some code to just fetch the thumbnail of the video when the page loads and attach a click event listener to it, to play the video.

Place this code in the youtube-embed.js file to display the placeholder image of the video:

window.addEventListener("load", function(){
    var v = document.getElementsByClassName("youtube-video");
    for (var n = 0; n < v.length; n++) {
        var p = document.createElement("div");
        p.innerHTML = '<img class="youtube-thumb" src="//i.ytimg.com/vi/' + v[n].dataset.id + '/hqdefault.jpg"><div class="play-button"></div>';
        p.onclick = youtube_video_clicked;
        v[n].appendChild(p);
    }
}, false);

In the above video, we find all the DOM elements with class name youtube-video and retrieve the data-id attribute value. Then we add an img tag inside the youtube-video class named div tag pointing to the placeholder image of the video.

To enqueue this script, place the following code in your youtube-embed.php file:

function register_youtube_embed_plugin_scripts() 
{
	wp_register_script("youtube-embed-js", plugins_url("youtube-embed/youtube-embed.js"));
	wp_enqueue_script("youtube-embed-js");
}

add_action("wp_enqueue_scripts", "register_youtube_embed_plugin_scripts");

Now, when you view the post using your shortcode, you’ll see something like this:

YouTube Plugin Preview

We also want to load the iframe when a user clicks on the placeholder image to play the video. To do this, place the following code in the youtube-embed.js file:

function youtube_video_clicked() {
    var iframe = document.createElement("iframe");
    iframe.setAttribute("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
    iframe.setAttribute("frameborder", "0");
    iframe.setAttribute("id", "youtube-iframe");
    this.parentNode.replaceChild(iframe, this);
}

When a user clicks on the placeholder image, the iframe tag is embedded with the autoplay attribute set to true. Now, clicking on the placeholder image will play the video.

Making the Video Responsive

To make the video responsive, place this CSS code in the youtube-embed.css file:

.youtube-container-child
{
	position: relative;
	padding-bottom: 56.25%; /* 16:9 */
	padding-top: 25px;
	height: 0;
}

.youtube-container-child iframe, .youtube-container-child img
{
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
}

To enqueue the script, place the following code in the youtube-embed.php file:

function register_youtube_embed_plugin_styles() 
{
    wp_register_style("youtube-embed-css", plugins_url("youtube-embed/youtube-embed.css"));
    wp_enqueue_style("youtube-embed-css");
}

add_action("wp_enqueue_scripts", "register_youtube_embed_plugin_styles");

Now, our video should look like this:

YouTube Plugin Preview - Improved

Creating a Shortcode Button

Typing the shortcode to add a video is cumbersome, so let’s create a text editor button that will display a prompt to enter the video ID and add the shortcode to the post editor.

Firstly, to add a button to the WordPress text editor, we need to use Quicktags API.

Place this code in youtube-embed.php file to display the button:

function youtube_shortcode_text_editor_script() 
{
    if(wp_script_is("quicktags"))
    {
        ?>
            <script type="text/javascript">

                QTags.addButton( 
                    "youtube_shortcode", 
                    "Youtube Embed", 
                    youtube_callback
                );

                function youtube_callback()
                {
                	var id = prompt("Please enter your video id");

					if (id != null) 
					{
						QTags.insertContent('[youtube id="'+id+'"][/youtube]');
					}
                }
            </script>
        <?php
    }
}

add_action("admin_print_footer_scripts", "youtube_shortcode_text_editor_script");

Here, we’re adding a button named youtube_shortcode. When a user clicks the button, youtube_callback is fired to take the user input and add the shortcode.

Here’s what it looks like in the text editor:

YouTube Shortcode Button

Creating a Visual Editor Button to Add a Shortcode

Similarly, we can add a button to the visual editor. For this we need to create a TinyMCE plugin.

Place this code in the youtube-embed.php file to register a TinyMCE plugin:

function enqueue_mce_plugin_scripts($plugin_array)
{
    //enqueue TinyMCE plugin script with its ID.
    $plugin_array["youtube_button_plugin"] =  plugin_dir_url(__FILE__) . "mce.js";
    return $plugin_array;
}

add_filter("mce_external_plugins", "enqueue_mce_plugin_scripts");

function register_mce_buttons_editor($buttons)
{
    //register buttons with their id.
    array_push($buttons, "youtube");
    return $buttons;
}

add_filter("mce_buttons", "register_mce_buttons_editor");

Next, we need to write the JavaScript functionality to display a prompt to take the ID as input and add our shortcode. To do this, place the following code in the mce.js file:

(function() {
    tinymce.create("tinymce.plugins.youtube_button_plugin", {

        init : function(ed, url) {

            //add new button     
            ed.addButton("youtube", {
                title : "Youtube Embed",
                cmd : "youtube_command",
                image : "https://cdn3.iconfinder.com/data/icons/free-social-icons/67/youtube_square_color-32.png"
            });

            //button functionality.
            ed.addCommand("youtube_command", function() {
                var id = prompt("Please enter your video id");
                if (id != null) 
                {
                    ed.execCommand("mceInsertContent", 0, '[youtube id="'+id+'"][/youtube]');
                }
            });
        },

        createControl : function(n, cm) {
            return null;
        },

        getInfo : function() {
            return {
                longname : "Extra Buttons",
                author : "Narayan Prusty",
                version : "1"
            };
        }
    });

    tinymce.PluginManager.add("youtube_button_plugin", tinymce.plugins.youtube_button_plugin);
})();

We now add a button named youtube, when user clicks on the button we execute the youtube_command callback.

Here’s how it looks:

YouTube Shortcode Button in the Visual Editor

Conclusion

In this tutorial, we saw how to create a YouTube embed plugin that can embed YouTube videos without increasing page size and also making our videos responsive. This is a small, but very useful plugin.

Frequently Asked Questions about Creating a YouTube Embed Plugin for WordPress

How can I customize the YouTube embed plugin for my WordPress site?

Customizing your YouTube embed plugin can greatly enhance the user experience on your site. You can adjust the size of the video player, autoplay settings, and even the color scheme to match your website’s theme. To do this, you need to access the plugin settings in your WordPress dashboard. Here, you can modify various parameters such as width, height, autoplay, loop, controls, and more. Remember to save your changes before exiting.

Can I embed multiple YouTube videos on my WordPress site using the plugin?

Yes, you can embed multiple YouTube videos on your WordPress site using the plugin. You just need to repeat the process of copying the video URL and pasting it into the plugin’s embed code generator. You can then place these generated codes in different parts of your website, such as blog posts, pages, or widgets.

Is it possible to make the YouTube video responsive on my WordPress site?

Absolutely. Making your YouTube video responsive means it will automatically adjust to fit the screen size of the device your visitor is using. This can be achieved by adding some CSS code to your theme’s stylesheet. The code will ensure that the video maintains its aspect ratio while fitting into different screen sizes.

How can I disable related videos from showing at the end of a YouTube video on my WordPress site?

Disabling related videos can be done through the plugin settings. There’s usually an option labeled “Show related videos” or something similar. Simply uncheck this option and save your changes. This will prevent YouTube from showing other videos at the end of your embedded video.

Can I add a YouTube video to a widget area on my WordPress site?

Yes, you can add a YouTube video to a widget area on your WordPress site. After generating the embed code using the plugin, go to Appearance > Widgets in your WordPress dashboard. Drag and drop a Text widget to your desired widget area and paste the embed code into the widget. Click Save to finish.

How can I add captions to the YouTube videos on my WordPress site?

If the video already has captions on YouTube, they will automatically appear when the video is played on your site. However, if you want to add your own captions, you can do so by using a video editing software before uploading the video to YouTube.

Is it possible to embed a YouTube playlist on my WordPress site?

Yes, it’s possible to embed a YouTube playlist on your WordPress site. The process is similar to embedding a single video. You just need to copy the playlist’s URL from YouTube and paste it into the plugin’s embed code generator.

Can I control the start and end time of a YouTube video on my WordPress site?

Yes, you can control the start and end time of a YouTube video on your WordPress site. This can be done by adding “?start=X&end=Y” at the end of the video URL, where X and Y are the start and end times in seconds.

How can I make the YouTube video autoplay on my WordPress site?

To make a YouTube video autoplay on your WordPress site, you need to add “?autoplay=1” at the end of the video URL in the embed code. However, keep in mind that autoplay can be intrusive for some users, so use it sparingly.

Is the YouTube embed plugin compatible with all WordPress themes?

The YouTube embed plugin should be compatible with most WordPress themes. However, there may be some exceptions due to the vast number of themes available. If you encounter any issues, try reaching out to the theme developer or the plugin support for assistance.

Narayan PrustyNarayan Prusty
View Author

Narayan is a web astronaut. He is the founder of QNimate. He loves teaching. He loves to share ideas. When not coding he enjoys playing football. You will often find him at QScutter classes.

ChrisBombedshortcodevideoWordPressWordPress VideoYoutube
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week