Remove type attribute for Javascript and style in WordPress

0
279

Mostaly wordpress website facing a problem with W3 Validator that constantly show some Warnings : ” The type attribute is unnecessary for JavaScript resources.” in my WordPress Website. Also i have already another one that is: “The type attribute is unnecessary for style resources”. In total i have 30 repeated Warnings that invalidate my website.  After make some research i have found that HTML 5 doesn’t require anymore to declare type attribute for JavaScript tags and style. So practically if you have:

  1. <script type=“text/javascript”>
<script type="text/javascript">

you have to remove the type=”text/javascript”

  1. <script>
<script>

The same thing have to be done with style tags:

  1. <style type=“text/css”>
<style type="text/css">

and replace with:

  1. <style>
<style>

Now with an html this is easy to edit and to fix the Warnings but isn’t the same with WordPress that files are called with wp_enqueue_script or wp_enqueue_style functions. In this case WordPress gives to 2 hooks to give to us to remove the type attribute from JavaScript and style tags loaded from WordPress native functions.

The two hooks are: 

style_loader_tag – HTML link tag of an enqueued style

script_loader_tag – Html ling tag of the enqueued script

So i created an function called codeles_remove_type_attr  that with a reg expression remove the type attribute from WordPress loaded JavaScript and Styles tags.

After that i have added two filters one for the style tag hook and the other one for the script hook.

The code below have to be written into functions.php file.

  1. add_filter(‘style_loader_tag’, ‘codeless_remove_type_attr’, 10, 2);
  2. add_filter(‘script_loader_tag’, ‘codeless_remove_type_attr’, 10, 2);
  3. function codeless_remove_type_attr($tag, $handle) {
  4. return preg_replace( “/type=[‘”]text/(javascript|css)[‘”]/”, , $tag );
  5. }
add_filter('style_loader_tag', 'codeless_remove_type_attr', 10, 2);
add_filter('script_loader_tag', 'codeless_remove_type_attr', 10, 2);

function codeless_remove_type_attr($tag, $handle) {
    return preg_replace( "/type=['"]text/(javascript|css)['"]/", '', $tag );
}

Now the problem is resolved but all the WordPress plugins and themes have to do that so we can’t fall in the problem to add the function in all of them manually.manualy data chaeck plugin and theme