script_loader_tag 函数是如何工作的?

Lin*_* M. 3 php wordpress

我已经在functions.php、WordPress 中看到了script_loader_tag 函数,但我很难完全理解它是如何工作的。

例如,我见过这样的例子:

function add_async_defer($tag, $handle) {

    if('googlemaps' !== $handle) {
        return $tag;
    }
    return str_replace(' src', 'async="async" defer="defer" src', $tag);
}
add_filter('script_loader_tag', 'add_async_defer', 10, 2);
Run Code Online (Sandbox Code Playgroud)

它用于为 Google Maps API 生成脚本标签:

<script type='text/javascript'async="async" defer="defer" src='https://maps.googleapis.com/maps/api/js?key=AIzaSyBz02VRxO_dgaKsBS62TLL6AW4McNTQiKU&#048;callback=initMap&#038;ver=5.2.1'></script>
Run Code Online (Sandbox Code Playgroud)

但是 $tag 和 $handle 参数是什么意思呢?

add_filter 末尾的数字 10 和 2 是什么意思?

这个功能可以修改为仅在特定页面有条件地显示标签吗?

Fah*_*ikh 6

参数定义如下:

$tag:排队脚本的标签。

$handle:脚本的注册句柄。例如,由 WordPress 入队的 jQuery 具有句柄“jquery”

数字10表示 WordPress 队列中回调函数的优先级,以处理所有挂在script_loader_tag钩子上的函数。

数字2表示回调函数中允许的参数数量。

@chinLeung 也给出了参考答案。


考虑到您的代码示例,以下内容应进一步解释:

function add_async_defer($tag, $handle, $src) {
    if('googlemaps' !== $handle) {//Here we check if our handle is googlemaps
        return $tag; //We return the entire <script> tag as is without modifications.
    }
    return "<script type='text/javascript' async='async' defer='defer' src='".$src."'></script>";//Usually the value in $tag variable looks similar to this script tag but without the async and defer
}
add_filter('script_loader_tag', 'add_async_defer', 10, 3);
Run Code Online (Sandbox Code Playgroud)