WordPress资产处理简介

tech2022-12-24  66

As a WordPress theme or plugin developer, there will come a time during your development process that you will need to include third party scripts or stylesheets in your plugin or theme. Sure, simply linking the assets in the header or footer would definitely work, but adhering to standard practice using the provided WordPress API will ensure that your theme or plugin will play nice with other plugins in the WordPress ecosystem.

作为WordPress主题或插件开发人员,在开发过程中会有一段时间需要在插件或主题中包含第三方脚本或样式表。 当然,只需在页眉或页脚中链接资产绝对可以,但是使用提供的WordPress API遵循标准做法将确保您的主题或插件与WordPress生态系统中的其他插件兼容。

If you want to provide maximum compatibility with other plugins and themes available, asset handling in WordPress is definitely a skill you should master.

如果要提供与其他可用插件和主题的最大兼容性,WordPress中的资产处理绝对是您应该掌握的技能。

This article is targeted to the beginner WordPress developer, with the assumption that you have a working knowledge of how WordPress action and filter hooks work.

本文针对初学者WordPress开发人员,假设您具有WordPress操作和过滤器挂钩如何工作的知识。

基础 (The Basics)

WordPress has provided a few basic functions to help the developer correctly load custom assets of their theme or plugin. The four main functions that you will use frequently are wp_register_script, wp_enqueue_script, wp_register_style and wp_enqueue_style.

WordPress提供了一些基本功能来帮助开发人员正确加载其主题或插件的自定义资产。 您将经常使用的四个主要功能是wp_register_script , wp_enqueue_script , wp_register_style和wp_enqueue_style 。

Let’s go through these four major functions one by one.

让我们一一介绍这四个主要功能。

wp_register_script( $handle, $src, $deps, $ver, $in_footer ); (wp_register_script( $handle, $src, $deps, $ver, $in_footer );)

I’m just going to go ahead and paste the description provided in the codex for this function.

我将继续粘贴此功能在法典中提供的描述。

Registers a script file in WordPress to be linked to a page later, which safely handles the script dependencies.

在WordPress中注册脚本文件以稍后链接到页面,该文件可以安全地处理脚本依赖项。

Only $handle and $src arguments are required, while the latter three is optional.

仅需要$handle和$src参数,而后三个参数是可选的。

$handle is the name of the script and should be unique. This is the most important part when enqueuing your script as the $handle will be the identifier of which script is to be loaded.

$handle是脚本的名称,并且应该是唯一的。 这是使脚本排队时最重要的部分,因为$handle将是要加载该脚本的标识符。

$src is the URL to the script. You can get the proper URL using provided built in functions such as plugin_url(), get_template_directory_uri() and get_stylesheet_uri(). For a remote URL, protocol-agnostic URL such as //ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js can be used.

$src是脚本的URL。 您可以使用提供的内置函数(例如plugin_url() , get_template_directory_uri()和get_stylesheet_uri()获得正确的URL。 对于远程URL,可以使用与协议无关的URL,例如//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js 。

$deps should be an array of scripts’ handle of which your script depends on. By defining them here, WordPress will load those dependencies first before loading your custom scripts.

$deps应该是脚本所依赖的脚本句柄数组。 通过在此处定义它们,WordPress将在加载自定义脚本之前先加载这些依赖项。

$ver is simply your script’s version, and it will be appended as a query string in your src parameter of script tag.

$ver只是脚本的版本,它将作为查询字符串附加到script标签的src参数中。

$in_footer is a Boolean flag that will tell WordPress whether to load your script in head section of document, or in the footer instead. Make sure that the theme properly includes wp_head() and wp_footer() correctly for this to work.

$in_footer是一个布尔型标志,它将告诉WordPress是否将脚本加载到文档的head部分,还是放在页脚中。 确保主题正确包含wp_head()和wp_footer()才能正常工作。

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); (wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );)

This function is similar to wp_register_script with the exception that only $handle parameter is required. If you have already registered your scripts prior to execution using wp_register_script, you can directly enqueue them using wp_enqueue_script('your-registered-handle').

该函数类似于wp_register_script ,不同之处在于仅需要$handle参数。 如果在执行之前已经使用wp_register_script注册了脚本,则可以使用wp_enqueue_script('your-registered-handle')直接将其加入wp_enqueue_script('your-registered-handle') 。

This is the actual function that will link your script to the generated page, so this function needs to be used in conjunction to wp_register_script.

这是将您的脚本链接到生成的页面的实际功能,因此需要将此功能与wp_register_script结合使用。

wp_register_style( $handle, $src, $deps, $ver, $media ); (wp_register_style( $handle, $src, $deps, $ver, $media );)

This is the counterpart function for wp_register_script, only that this function will handle all your stylesheet registration. Let’s go through each of the arguments for this function.

这是wp_register_script的对应函数,仅此函数将处理所有样式表注册。 让我们遍历此函数的每个参数。

$handle is the unique identifier to your stylesheet, similar to the one for your wp_register_script and wp_enqueue_script. This is a required parameter and your handle should be unique to your WordPress installation.

$handle是样式表的唯一标识符,类似于wp_register_script和wp_enqueue_script 。 这是必填参数,并且您的句柄对于WordPress安装应该是唯一的。

$src will be the URL to your CSS file. Again, you can either link it to the local file in your theme or plugin, and it also works with a remote URL.

$src将是您CSS文件的URL。 同样,您可以将其链接到主题或插件中的本地文件,并且还可以与远程URL一起使用。

$deps will handle all your CSS’s dependency, which should be defined as an array of the styles handles.

$deps将处理所有CSS的依赖项,应将其定义为样式句柄的数组。

$ver is optional parameter where you can define your CSS version, and it will be appended to the URL as the query string as well.

$ver是可选参数,您可以在其中定义CSS版本,并将其作为查询字符串附加到URL后面。

$media is the CSS media types of your CSS. The complete list of acceptable value can be found on this page.

$media是CSSCSS媒体类型。 可接受值的完整列表可在此页面上找到。

wp_enqueue_style( $handle, $src, $deps, $ver, $media ); (wp_enqueue_style( $handle, $src, $deps, $ver, $media );)

This function will link your CSS to the generated page, similar to how wp_enqueue_script works. So basically, you can either enqueue your previously registered CSS, or you can enqueue the CSS on the go by defining the $src parameter as well.

此功能会将您CSS链接到生成的页面,类似于wp_enqueue_script工作方式。 因此,基本上,您可以将以前注册CSS放入队列中,也可以通过定义$src参数随时在队列中放入CSS。

我们什么时候入队? (When Do We Enqueue Them?)

There are three proper hooks recommended to enqueue your scripts and stylesheets.

建议使用三个合适的钩子来加入脚本和样式表。

Use wp_enqueue_scripts action hook whenever you want to enqueue your script to the front end of your site. Don’t be confused with the name, as the same hook can be used to enqueue your style as well.

要将脚本排入站点前端时,请使用wp_enqueue_scripts操作挂钩。 不要与名称混淆,因为相同的钩子也可以用来加入您的样式。

How about the admin page? Well, you can hook your enqueue function on the admin_enqueue_scripts and all your scripts and styles will be loaded on the administrative side of things correctly. To load your scripts and styles specifically on the login page, login_enqueue_scripts action hook is provided.

管理员页面如何? 好了,您可以将自己的入队功能挂接到admin_enqueue_scripts ,所有脚本和样式都将正确地加载到事物的管理方面。 要专门在登录页面上加载脚本和样式,提供了login_enqueue_scripts操作挂钩。

入队与注册 (Enqueue Versus Register)

At a glance, it seems redundant to register your scripts and stylesheets first, before enqueuing them. So why do we need to use wp_register_script and wp_register_style in the first place, when in reality we can directly just use wp_enqueue_script and wp_enqueue_style instead? Well, technically, you don’t need to.

乍一看,在将脚本和样式表放入队列之前先注册它们似乎是多余的。 那么为什么我们首先需要使用wp_register_script和wp_register_style ,而实际上我们可以直接使用wp_enqueue_script和wp_enqueue_style ? 好吧,从技术上讲,您不需要。

But if you want to dynamically load your scripts and stylesheets based on various conditions, you better register them first so you can enqueue them anytime you want at any point of execution without repeating yourself.

但是,如果要根据各种条件动态加载脚本和样式表,则最好先注册它们,以便您可以在任何需要的任何时间在任何执行点将它们排队,而无需重复自己的操作。

Let’s look at this simple example:

让我们看一个简单的例子:

wp_register_script( 'my-custom-js', ... ); wp_register_script( 'my-second-js', ... ); if ( is_page( 32 ) ) { wp_enqueue_script('my-custom-js'); } if ( $var ) { wp_enqueue_script('my-second-js'); }

Based on this snippet, you can see that we first register two custom scripts, my-custom-js and my-second-js. Based on several conditions, in this case, when the page loaded is of ID 32, or $var is set to true, we can dynamically enqueue them.

根据此片段,您可以看到我们首先注册了两个自定义脚本my-custom-js和my-second-js 。 在这种情况下,基于多种条件,当加载的页面的ID为32或$var设置为true ,我们可以动态地将它们加入队列。

Registering them first is also useful whenever you want to rely on the same script on a different part of the website. As pointed out earlier, there are two different hooks that need to be used in order to load your scripts and stylesheets on front end facing side and administrative side. So by registering them first, you would just need to register them once, and enqueue them in both related hooks.

每当您要依赖网站另一部分上的相同脚本时,先注册它们也很有用。 如前所述,有两个不同的钩子需要使用,以便在面向前端和管理端的位置加载脚本和样式表。 因此,通过首先注册它们,您只需要注册一次,并将它们放入两个相关的钩子中。

已经包含什么? (What’s Already Included?)

Many developers resort to including a third party library of their own, which then leads to big plugin or theme sizes and the potential for incompatibilities. WordPress includes some useful JavaScript libraries of its own, so why not utilize that instead?

许多开发人员诉诸于包括自己的第三方库,这会导致较大的插件或主题大小以及潜在的不兼容性。 WordPress包括一些自己的有用JavaScript库,那么为什么不利用它呢?

An exhaustive list of what’s already included with its respective handle is listed on this page under Handles and Their Script Paths Registered by WordPress section. This list may get outdated, so if you want to peek directly at the source, take a look at wp-includes/script-loader.php source code, specifically inside the wp_default_scripts function.

此页面下“ 句柄及其由WordPress注册的脚本路径”部分列出了其相应句柄已包含的详尽列表。 此列表可能会过时,因此,如果您想直接查看源代码,请查看wp-includes/script-loader.php源代码,特别是wp_default_scripts函数内部。

You can find a lot of useful libraries that can be reused without the need of shipping it inclusively with your plugin or theme.

您可以找到许多有用的库,这些库可以重复使用,而无需与您的插件或主题一起提供。

附加功能 (Additional Functionalities)

Besides the four main functions to register and enqueue your scripts and styles, WordPress also provides a handful of functions that can help with regards to managing your plugin or theme assets. Let’s take a look at some of them.

除了注册和排队脚本和样式的四个主要功能外,WordPress还提供了一些功能,可帮助您管理插件或主题资产。 让我们看看其中的一些。

使用wp_localize_script使PHP变量在客户端wp_localize_script (Making Your PHP Variables Available on the Client Side with wp_localize_script)

Although this function is primarily used to provide proper localized translation of strings (thus the name) to your client side code, it can be used virtually to make any data that you have on the server side available on the client side as well.

尽管此功能主要用于向客户端代码提供适当的字符串本地化翻译(因此,名称),但实际上,该功能可用于使服务器端拥有的所有数据也可以在客户端使用。

wp_localize_script( $handle, $name, $data );

As the above code suggests, this function will accept three required parameters. $handle refers to the handle of the script you are attaching the data for. It is important to note that the script must be either registered or enqueued first to make sure wp_localize_script works correctly.

如上面的代码所示,此函数将接受三个必需的参数。 $handle指的是您要为其附加数据的脚本的句柄。 重要的是要注意脚本必须先注册或入队,以确保wp_localize_script正常工作。

$name is the variable name that will be available on the client side, and will contain all your specified $data that you defined in an array.

$name是在客户端可用的变量名,它将包含您在数组中定义的所有指定的$data 。

Here’s a simple snippet to explain what this function does:

这是一个简单的代码片段,用于解释此功能的作用:

wp_register_script( 'my-custom-js', ... ); $args = array( 'foo' => 'bar' ); wp_localize_script( 'my-custom-js', 'my_var', $args ); wp_enqueue_script( 'my-custom-js' );

When the my-custom-js is enqueued, WordPress will handle the given data to make it available on the client side code. Since the $args will be JSON-encoded and assigned to the variable called my_var, you can always access the value back in your script like you normally do on any JavaScript object.

将my-custom-js放入队列后,WordPress将处理给定的数据以使其可在客户端代码上使用。 由于$args将经过JSON编码并分配给名为my_var的变量,因此您可以像通常对任何JavaScript对象进行操作一样,始终访问脚本中的值。

<script> console.log( my_var.foo ); // print out "bar" in console </script>

使用wp_enqueue_media将WordPress媒体库的所有相关脚本wp_enqueue_media (Enqueuing All Related Scripts for WordPress Media Library with wp_enqueue_media)

If you want to use the native WordPress media uploader in your plugin or theme, you will need to enqueue all the related assets required before you can access all the available related APIs. To make things easier, WordPress provides a helper function that will help you enqueue all the related scripts, styles and templates related to the Media API.

如果要在插件或主题中使用本机WordPress媒体上载器,则需要先排队所需的所有相关资产,然后才能访问所有可用的相关API。 为了使事情变得更容易,WordPress提供了一个帮助程序功能,可以帮助您使与媒体API相关的所有相关脚本,样式和模板入队。

wp_enqueue_media( $args );

The only parameter is $args, which is optional, and can be used if you want to enqueue all related assets associated with a specific post. I won’t delve too much into how to use the available API to implement the native media uploader in your plugin or theme since it deserves an article on its own, but here’s a little snippet to get you started.

唯一的参数是$args ,它是可选的,如果要使与特定帖子关联的所有相关资产入队,则可以使用该参数。 我不会过多地研究如何使用可用的API在您的插件或主题中实现本机媒体上载器,因为它本身应该有一篇文章,但是这里有一些摘要可以帮助您入门。

wp_enqueue_media(); // basic usage, enqueue all related scripts, styles and templates wp_enqueue_media( array( 'post' => 32 ) ); // enqueue all related assets for post with ID of 32

使用wp_style_add_data将元数据添加到样式表 (Adding Metadata to Stylesheet with wp_style_add_data)

This function works only for the stylesheet, and is particularly useful when you want to add metadata such as conditional comments, RTL support and an alternate title to your custom stylesheet.

此功能仅适用于样式表,当您要向自定义样式表中添加条件注释,RTL支持和备用标题等元数据时,此功能特别有用。

wp_style_add_data( $handle, $key, $value );

All three parameters are required. Let’s go through each of them to see what they represent.

所有三个参数都是必需的。 让我们遍历每个对象,看看它们代表什么。

$handle is the specific stylesheet handle that we want to add our metadata to.

$handle是要将元数据添加到的特定样式表句柄。

$key is the data point. There are five accepted values which are conditional, rtl, suffix, alt and title

$key是数据点。 有五个可接受的值,它们是conditional , rtl , suffix , alt和title

$value is the data string in conjunction to the previously specified $key.

$value是与先前指定的$key关联的数据字符串。

Here’s a example snippet on how we can take advantage of this function to load our stylesheet specific to Internet Explorer only.

这是一个示例片段,说明如何利用此功能来加载仅针对Internet Explorer的样式表。

wp_enqueue_style( 'custom-ie-style', get_template_directory_uri() . '/css/ie.css' ); wp_style_add_data( 'custom-ie-style', 'conditional', 'IE' );

That’s it! Once your stylesheet is linked to the generated page, this is what is actually printed on the head part of the document.

而已! 将样式表链接到生成的页面后,这就是实际打印在文档head的内容。

<!--[if IE]> <link rel="stylesheet" id="custom-ie-style-css" href="http://www.example.com/wp-content/themes/example/css/ie.css" type="text/css" media="all"> <![endif]-->

使用filemtime自动缓存清除 (Automatically Cache Busting Using filemtime)

This is not actually WordPress specific, but I kept finding myself using this code time and again in my client projects. What it actually does is take advantage of the version argument in the wp_enqueue_script and related functions as a cache busting method by checking the file last modified time. Obviously, this only works for the local file, since we are using filemtime PHP function to detect the last modified timestamp of that file.

这实际上不是特定于WordPress的,但是我一直在客户项目中一次又一次地使用此代码。 它实际上所做的是通过检查文件的上次修改时间来利用wp_enqueue_script中的version参数和相关功能作为缓存清除方法。 显然,这仅适用于本地文件,因为我们正在使用filemtime PHP函数来检测该文件的最后修改的时间戳。

Here’s how we define the version argument, in example of wp_enqueue_script function:

在wp_enqueue_script函数示例中,这是我们定义版本参数的wp_enqueue_script :

wp_enqueue_script( 'my-custom-js', get_template_directory_uri() . '/js/custom.js', array(), get_template_directory() . 'js/custom.js' );

Note that filemtime requires the path of your file, not the URL, thus in above snippet, we are using get_template_directory function instead to get the path to our theme directory.

请注意, filemtime需要文件的路径,而不是URL,因此在上面的代码段中,我们使用get_template_directory函数来获取主题目录的路径。

From now onwards, any modifications to the file will result in different version value, and our query string will get updated accordingly.

从现在开始,对该文件的任何修改将产生不同的版本值,并且我们的查询字符串将相应地更新。

结论 (Conclusion)

As a responsible WordPress developer, it’s vital that you to apply best practices to your development process, and that includes learning how to properly load assets in your custom plugin or theme. This will ensure your plugin or theme is compatible with other plugins or themes, as well as reducing conflicts and bugs as WordPress evolves.

作为负责任的WordPress开发人员,对您的开发过程应用最佳实践至关重要,其中包括学习如何在自定义插件或主题中正确加载资产。 这将确保您的插件或主题与其他插件或主题兼容,并减少随着WordPress的发展而发生的冲突和错误。

翻译自: https://www.sitepoint.com/an-introduction-to-asset-handling-in-wordpress/

最新回复(0)