How to find WordPress theme’s stylesheet handle

A few moments ago, I wanted to append an inline style to the theme’s stylesheet from within a plugin. This requires knowing the current theme’s stylesheet handle, so here is a function that finds that string.

private function find_theme_stylesheet_handle() {
	global $wp_styles;

	foreach( $wp_styles->registered as $handle => $style_obj ) {
		if( $style_obj->src === get_template_directory_uri() . '/style.css' ) {
			return $handle;
		}
	}
	return null;
}
Published
Categorized as How to

2 comments

  1. This is a very cool function. My only note is about

    …append an inline style to the theme‚Äôs stylesheet from within a plugin…

    If I’m reading this correctly, you’re talking about appending to the theme’s style.css file. Two thoughts on this:

    1. Sometimes themes have a style.css but the actual CSS is loaded from a different file (e.g. in my personal theme the CSS is loaded from /css/style.min.css in the theme, though style.css still exists to provide WordPress the theme name and version).
    2. If a plugin modified my theme CSS on a website I was working on, I’d be likely to accidentally overwrite the changes when pushing my local changes up to the website.

    I know you work with some custom setups so you may have already thought through these points and determined they are not relevant in your case but I wanted to mention this in case someone else is reading this and considering doing something similar without considering these points.

    These blog posts are awesome. Thanks for posting them.

  2. Sal, thanks for helping me refine my thoughts, as always. Perhaps append is not the best word.

    I needed this function to pass into `wp_add_inline_style`, which includes inline styles on a page just after the include for a stylesheet file. No edits to theme files are made. It’s all about making sure the inline style is inserted into the document at the appropriate place.

Leave a comment

Your email address will not be published. Required fields are marked *