I want to clean up <script> tags generated by WordPress to produce more semantic output for HTML5.

You can already do this for <style> tags using this code attached to the style_loader_tag filter:

//clean up the default WordPress style tags
add_filter('style_loader_tag', 'clean_style_tag');

function clean_style_tag($input) {
    preg_match_all("!<link rel="stylesheet"\s?(id='[^']+')?\s+href="https://wordpress.stackexchange.com/questions/50439/(.*)" type="text/css" media="https://wordpress.stackexchange.com/questions/50439/(.*)" />!", $input, $matches);

    //only display media if it's print
    $media = $matches[3][0] === 'print' ? ' media="print"' : '';                                                                             
    return '<link rel="stylesheet" href="' . $matches[2][0] . '"' . $media . '>' . "\n";
}

But there isn’t an equivalent script_loader_tag in core yet. It was proposed in the past, but for now we need a workaround.

I’ve started looking in /wp-includes/class.wp-scripts.php at function do_item( $handle, $group = false ) around line 79 which holds the script output (specifically lines 117-120), but I’m having a bit of trouble finding an appropriate filter that could be used here.

2 Answers
2

If you really want to do this, then it should already be possible.

The global $wp_scripts is an instance of the WP_Scripts class, which is an instance of the WP_Dependencies class.

So in theory (not tested), you should be able to do something like this:

function alter_script_tags()
{
    echo '<pre>';
        print $GLOBALS['wp_scripts']->print_html;
    echo '</pre>';
}
add_action( 'wp_enqueue_scripts', 'alter_script_tags', 999999 );

This is just a rough sketch, but you should get the idea.

Leave a Reply

Your email address will not be published. Required fields are marked *