1

Due to W3C validation warnings that I would like to avoid, I currently use the following snippet in my functions file to remove the type attribute from enqueued scripts and stylesheets:

// 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 );
}

But this doesn't work on files loaded by plugins. Does anyone know of a solution to this problem?

Jeremy
  • 239
  • 2
  • 14

1 Answers1

0

You could capture the whole output content of WordPress with a simple tweak: https://stackoverflow.com/a/22818089/5556440

Look at @kfriend's answer from the question provided above.

<!-- 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);

Then inside the newly final_output filter, perform your 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);
}
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
  • the snippet is ok, but now i got this error from w3c validator : "Non-space character in page trailer." – Torgia Feb 19 '18 at 09:30
  • @Torgia https://stackoverflow.com/questions/42568560/html-validation-error-non-space-character-in-page-trailer – Chin Leung Feb 19 '18 at 15:10