Created
April 6, 2019 10:52
-
-
Save vishaldodiya/cec34bf2b18cce5db156bb569253810d to your computer and use it in GitHub Desktop.
Add attributes to Wordpress Enqueueing/ Registering Scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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