博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何为WordPress创建YouTube嵌入插件
阅读量:2505 次
发布时间:2019-05-11

本文共 9943 字,大约阅读时间需要 33 分钟。

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.

YouTube是最受欢迎的视频共享平台。 众所周知,他们还让我们将其视频嵌入到我们的网站中。 但是仅将嵌入代码粘贴到我们的网站中是不够的。 它没有响应能力,给我们的页面增加了很多不必要的分量。 由于这些问题,用户不太可能播放视频,因此我们冒着风险离开我们的网站。

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.

在本教程中,我将向您展示如何创建YouTube嵌入插件,该插件提供了一个短代码,可以在不增加页面权重的情况下以响应方式添加YouTube视频。

WordPress默认嵌入 (WordPress Default Embeds)

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

默认情况下,WordPress在帖子编辑器中将YouTube URL转换为嵌入代码(使用oEmbed)。

For example:

例如:

Check out this video:http://www.youtube.com/watch?v=dQw4w9WgXcQ

..is converted to:

..转换为:

Check out this video:

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.

WordPress不会对我们的视频显示进行任何其他优化,例如使其具有响应性,或者动态加载视频以减小页面大小。 通过一些工作,我们可以对WordPress默认情况下处理YouTube视频的方式进行重大改进。

YouTube嵌入如何增加页面大小? (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!

YouTube让我们使用标准的iframe标签将视频嵌入到我们的网站中。 此嵌入代码可下载约1MB的资源,以便仅在页面加载时呈现视频。 同样,当我们单击播放按钮播放视频时,还会下载〜500KB的额外资源!

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 and ).

这会增加页面的加载时间,从而影响您的“页面速度”得分,众所周知,这是个坏消息(请和进一步阅读)。

YouTube嵌入式视频的响应能力 (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.

默认的YouTube嵌入代码没有响应。 视频的宽度为560像素,高度为315像素。 因此,如果您的网站具有响应能力,则用户使用小于560像素的屏幕查看您的网站可能会带来糟糕的用户体验。

让我们构建我们的插件! (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:

为了使该插件可安装,我们将以下代码放入youtube-embed.php文件中:

创建简码 (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.

让我们创建一个名为youtube的短代码,它使用YouTube视频ID,并生成HTML代码以在前端查看时显示视频。

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

这是创建简码的代码。 将此代码放在youtube-embed.php文件中:

function youtube_embed_callback($atts=null, $content=null){	extract($atts);	return "
";}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.

当您查看帖子时,您什么也看不到,因为我们没有显示iframe嵌入代码,而是显示了具有视频ID的div 。 仅当用户要播放视频时,我们才会动态加载嵌入代码,从而减少页面加载时间。

动态加载YouTube视频 (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:

将此代码放在youtube-embed.js文件中,以显示视频的占位符图像:

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 = '
'; 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.

在上面的视频中,我们找到了类名称为youtube-video所有DOM元素,并检索了data-id属性值。 然后,我们在名为div标签的youtube-video类内添加img标签,该标签指向视频的占位符图像。

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

要加入此脚本,请在youtube-embed.php文件中放置以下代码:

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:

当用户单击占位符图像以播放视频时,我们还希望加载iframe 。 为此,请将以下代码放入youtube-embed.js文件:

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.

当用户单击占位符图像时,将嵌入iframe代码,并将自动播放属性设置为true。 现在,单击占位符图像将播放视频。

使视频具有响应性 (Making the Video Responsive)

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

要使视频具有响应性,请将以下CSS代码放在youtube-embed.css文件中:

.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:

要使脚本入队,请将以下代码放入youtube-embed.php文件中:

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.

键入简码以添加视频很麻烦,因此让我们创建一个文本编辑器按钮,该按钮将显示提示输入视频ID并将简码添加到帖子编辑器中。

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

首先,要将按钮添加到WordPress文本编辑器,我们需要使用 。

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

将此代码放在youtube-embed.php文件中以显示按钮:

function youtube_shortcode_text_editor_script() {    if(wp_script_is("quicktags"))    {        ?>            
function youtube_shortcode_text_editor_script() {    if(wp_script_is("quicktags"))    {        ?>            

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.

在这里,我们添加了一个名为youtube_shortcode的按钮。 用户点击按钮后,就会触发youtube_callback接受用户输入并添加简码。

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

这是文本编辑器中的外观:

YouTube简码按钮

创建可视化编辑器按钮以添加简码 (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.

同样,我们可以在可视化编辑器中添加一个按钮。 为此,我们需要创建一个TinyMCE插件。

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

将此代码放在youtube-embed.php文件中以注册TinyMCE插件:

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:

接下来,我们需要编写JavaScript功能以显示提示,以ID作为输入并添加我们的简码。 为此,将以下代码放在mce.js文件中:

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

现在,我们添加了一个名为youtube的按钮,当用户单击该按钮时,我们将执行youtube_command回调。

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.

在本教程中,我们了解了如何创建YouTube嵌入插件,该插件可以嵌入YouTube视频而不增加页面大小,还可以使视频具有响应能力。 这是一个很小但非常有用的插件。

翻译自:

转载地址:http://nkrgb.baihongyu.com/

你可能感兴趣的文章
进程和线程概念及原理
查看>>
Dubbo超时重试机制带来的数据重复问题
查看>>
注解配置里的几个注解
查看>>
使ie678支持css3伪类选择器的插件
查看>>
题解报告:hdu 1212 Big Number(大数取模+同余定理)
查看>>
POJ 3624 Charm Bracelet
查看>>
ZOJ 2314 Reactor Cooling
查看>>
关于做事的一点想法
查看>>
程序在本地能启动而预发布不能启动
查看>>
Lucene、ES好文章
查看>>
有关定时器setTimeout()、setInterval()详解
查看>>
刷题总结——次小生成树(bzoj1977 最小生成树+倍增)
查看>>
html5-2 html实体和颜色有哪些
查看>>
饺紫猫配色教程
查看>>
第三百六十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)用Django实现搜索功能...
查看>>
第八十节,CSS3边框图片效果
查看>>
第一百九十五节,jQuery EasyUI,Resizable(调整大小)组件
查看>>
Gym 101128F Landscaping(网络流)题解
查看>>
使用Expression进行查询拼接
查看>>
父页面获得子页面的值
查看>>