How to add attribute in wordpress stylesheet tag?

Use style_loader_tag filter in wordpress to add attribute in wordpress stylesheet.

For Example: Your style name is header-style

function add_rel_preload( $html, $handle, $href, $media ) {
    if ( is_admin() ) {
        return $html;
    }
    
    $css_attr = array(
      'header-style',
    );

   if ( is_array( $css_attr ) && in_array( $handle, $css_attr,   true ) ) {
   return str_replace( " href=", ' rel="preload" as="style" href=', $html );
   }

  return $html;
}
add_filter( 'style_loader_tag', 'add_rel_preload', 10, 4 );

if you wants to add attributes more style just add your style name into  $css_attr array.

Example: $css_attr = array(
   'header-style',
   'footer-style',
);

Leave a comment