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; }
Comments
2 responses to “How to find WordPress theme’s stylesheet handle”
This is a very cool function. My only note is about
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, thoughstyle.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.
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.