How to add HTML attributes to HTML tags in WordPress

622 Views Asked by At

I am trying to figure out how to add attributes to an html tag. I am creating a child theme, and have enqueued a stylesheet that requires the crossorgin attribute. How would i go about adding this?

Current tag

 <link rel="stylesheet" id="bootstrap-css" 
 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
  rel="stylesheet" media="all">

Tag needed

 <link 
 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
 rel="stylesheet" integrity="sha384- 
 1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
1

There are 1 best solutions below

0
On

You can follow the below code according to your stylesheet.

wp_enqueue_style( 'bootstrap-css', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css', array(), null );

function add_jsdelivr_attributes( $html, $handle ) {
    if ( 'bootstrap-css' === $handle ) {
        return str_replace( "media='all'", "media='all' integrity='sha384- 
 1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3' crossorigin='anonymous'", $html );
    }
    return $html;
}
add_filter( 'style_loader_tag', 'add_jsdelivr_attributes', 10, 2 );