@@ -14,36 +14,47 @@ function update_script_tag( $handle = [], $add = [] ) {
1414 $ handle = (array ) $ handle ;
1515 $ add = (array ) $ add ;
1616
17- $ additions = '' ;
17+ $ attributes = [] ;
1818
1919 foreach ( $ add as $ type ) {
2020 switch ( $ type ) {
2121 case 'async ' :
22- $ additions . = ' async ' ;
22+ $ attributes [] = 'async ' ;
2323 break ;
2424 case 'defer ' :
25- $ additions . = ' defer ' ;
25+ $ attributes [] = 'defer ' ;
2626 break ;
2727 case 'module ' :
28- $ additions . = ' type="module" ' ;
28+ $ attributes [] = 'type="module" ' ;
2929 break ;
3030 case 'nomodule ' :
31- $ additions . = ' nomodule ' ;
31+ $ attributes [] = 'nomodule ' ;
3232 break ;
3333 }
3434 }
3535
36- if ( empty ( $ additions ) ) {
36+ if ( empty ( $ attributes ) ) {
3737 return ;
3838 }
3939
40- $ filter = function ( $ tag , $ current_handle ) use ( $ handle , $ additions ) {
40+ $ filter = function ( $ tag , $ current_handle ) use ( $ handle , $ attributes ) {
4141 // Bailout if the handle does not apply.
4242 if ( ! in_array ( $ current_handle , $ handle , true ) ) {
4343 return $ tag ;
4444 }
4545
46- return str_replace ( ' src ' , sprintf ( ' %s src ' , trim ( $ additions ) ), $ tag );
46+ // Remove existing attributes from attributes array if they are already set on a tag.
47+ foreach ( $ attributes as $ key => $ attribute ) {
48+ if ( preg_match ( "/\s {$ attribute }[\s>]/ " , $ tag ) ) {
49+ unset( $ attributes [ $ key ] );
50+ }
51+ }
52+
53+ if ( empty ( $ attributes ) ) {
54+ return $ tag ;
55+ }
56+
57+ return str_replace ( ' src ' , sprintf ( ' %s src ' , join ( ' ' , $ attributes ) ), $ tag );
4758 };
4859
4960 add_filter ( 'script_loader_tag ' , $ filter , 10 , 2 );
0 commit comments