Skip to content

Instantly share code, notes, and snippets.

@vishaldodiya
Created April 6, 2019 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishaldodiya/cec34bf2b18cce5db156bb569253810d to your computer and use it in GitHub Desktop.
Save vishaldodiya/cec34bf2b18cce5db156bb569253810d to your computer and use it in GitHub Desktop.
Add attributes to Wordpress Enqueueing/ Registering Scripts
<?php
/**
* Add attributes to script while enqueueing/registering.
*
* @param string $tag whole script tag of current enqueueing script.
* @param string $handle current enqueuing script handler.
*
* @return string
*/
function filter_script_loader_tag( $tag, $handle ) {
$attributes = array(
'async' => true,
);
// Add each attribute to tag if it's not been added already.
foreach ( $attributes as $key => $value ) {
if ( ! preg_match( ":\s$key(=|>|\s):", $tag ) ) {
if ( true === $value ) {
$attribute_string = sprintf( ' %s', esc_attr( $key ) );
} else {
$attribute_string = sprintf( ' %s="%s"', esc_attr( $key ), esc_attr( $value ) );
}
$tag = preg_replace(
':(?=></script>):',
$attribute_string,
$tag,
1
);
}
}
}
add_filter( 'script_loader_tag', 'filter_script_loader_tag', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment