Wordpress - Add 'title' attribute to stylesheets with wp_enqueue_style()

Okay, here's where I'm at with a solution.

wp_enqueue_style( 'my-handle', 'mystyle.css' );
global $wp_styles;
$wp_styles->add_data( 'my-handle', 'title', 'my_stylesheet_title' );

Don't like using the global. Is there something better?


It seems to me that you could also use style_loader_tag, see my other answer for a more detailed take on both style_loader_tag and script_loader_tag API:
How to add crossorigin and integrity to wp_register_style? (Font Awesome 5)

style_loader_tag is an official WordPress API, see the documentation: https://developer.wordpress.org/reference/hooks/style_loader_tag/

apply_filters( 'style_loader_tag', $html, $handle, $href, $media )
Filters the HTML link tag of an enqueued style.



First, enqueue your stylesheets

function add_styles() {
    // Example loading external stylesheet, could be used in both a theme and/or plugin
    wp_enqueue_style( 'font-awesome-5', 'https://use.fontawesome.com/releases/v5.5.0/css/all.css', array(), null );

    // Example theme
    wp_enqueue_style( 'font-awesome-5', get_theme_file_uri( '/assets/css/fontawesome.min.css' ), array(), null );

    // Example plugin
    wp_enqueue_style( 'font-awesome-5', plugins_url( '/assets/css/fontawesome.min.css', __FILE__ ), array(), null );
};
add_action( 'wp_enqueue_scripts', 'add_styles' );



Second, use style_loader_tag
Than use style_loader_tag to add your title to the specific stylesheet.

function add_stylesheet_attributes( $html, $handle ) {
    if ( 'font-awesome-5' === $handle ) {
        return str_replace( "rel='stylesheet'", "rel='stylesheet' title='something'", $html );
    }
    return $html;
}
add_filter( 'style_loader_tag', 'add_stylesheet_attributes', 10, 2 );

Looking at the file you mentioned in your post class.wp-styles.php, you have the following line, $tag .= apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n", $handle );. You can therefore hook into the "style_loader_tag" filter and add in the title tag. I like your answer as well, but am unsure as to which one would be better, as I am not sure if there are any issues with using the global or not.