【问题标题】:Remove the type attribute from scripts loaded by WordPress plugins从 WordPress 插件加载的脚本中删除 type 属性
【发布时间】:2018-02-06 19:35:45
【问题描述】:

由于我想避免 W3C 验证警告,我目前在我的函数文件中使用以下 sn-p 从排队的脚本和样式表中删除 type 属性:

// Remove type attribute from scripts and stylesheets
add_filter('style_loader_tag', 'remove_type_attr', 10, 2);
add_filter('script_loader_tag', 'remove_type_attr', 10, 2);
function remove_type_attr($tag, $handle) {
    return preg_replace( "/type=['\"]text\/(javascript|css)['\"]/", '', $tag );
}

但这不适用于插件加载的文件。有谁知道这个问题的解决方案吗?

【问题讨论】:

  • 您是否尝试过更改 add_filter 调用的执行优先级?

标签: php wordpress


【解决方案1】:

您可以通过简单的调整来捕获 WordPress 的整个输出内容:https://stackoverflow.com/a/22818089/5556440

查看@kfriend对上述问题的回答。

<!-- wp-content/mu-plugins/buffer.php -->
<?php

/**
 * Output Buffering
 *
 * Buffers the entire WP process, capturing the final output for manipulation.
 */

ob_start();

add_action('shutdown', function() {
    $final = '';

    // We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
    // that buffer's output into the final output.
    $levels = ob_get_level();

    for ($i = 0; $i < $levels; $i++) {
        $final .= ob_get_clean();
    }

    // Apply any filters to the final output
    echo apply_filters('final_output', $final);
}, 0);

然后在新的final_output 过滤器中,执行你的 preg_replace:

<!-- wp-content/themes/theme-name/functions.php -->
add_filter('final_out', 'remove_type_attr', 10, 2);
function remove_type_attr($content) {
    return preg_replace( "/type=['\"]text\/(javascript|css)['\"]/", '', $content);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多