1

I am currently using this code which works fine.

function add_data_attribute($tag, $handle) {
   if ( 'chargebee' !== $handle )
    return $tag;
    return str_replace( ' src', ' data-cb-site="mydomain" src', $tag );
}
add_filter('script_loader_tag', 'add_data_attribute', 10, 2);

However I need to combine this code with another tag:

function google_maps_script_attributes( $tag, $handle) {
    if ( 'google-maps' !== $handle ) {
        return $tag;
  }
    return str_replace( ' src', ' async="async" defer src', $tag );
}
add_filter('script_loader_tag', 'google_maps_script_attributes', 10, 2);

Should I call two separate functions as best practice, or is it faster and better to combine the two functions together somehow?

1

I think you could or even should combine your filters to keep your code DRY.

add_filter('script_loader_tag', function( $tag, $handle ) {

 if ( 'chargebee' == $handle ) :
    return str_replace( ' src', ' data-cb-site="mydomain" src', $tag );
 elseif( 'google-maps' == $handle ) :
    return str_replace( ' src', ' async="async" defer src', $tag );
 endif;

 return $tag;

}, 10, 2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.