Ideal inline dynamic CSS injection

wp_add_inline_style needs to be tied to an existing stylesheet in order to work properly. The inline styles will only be printed when the stylesheet they are attached to is enqueued. This is quite handy to control the scope of the inline styles. If the idea is to have them printed globally, the safest handle to tie them to is that of the active theme main stylesheet.

The way to attach the inline scripts to a stylesheet is by passing that stylesheet handle as the first parameter to wp_add_inline_style. The stylesheet handles may change depending on the theme and also depending on the viewed page, so they have to be found out. An easy way to know the full list of stylesheets and their handles loaded for a given page is using the following code:

global $wp_styles;
echo '<pre>' . var_export( wp_list_pluck( $wp_styles->registered, 'src', 'handle' ), true ) . '</pre>';

Supposing the theme’s main stylesheet handle is 'active-theme-style', then the call would be:

wp_add_inline_style( 'active-theme-style', $custom_css );

Some old or badly written themes might not load the css in a proper way. In that case, it’s safer to enqueue a stylesheet. If that’s not an option, this will work:

wp_enqueue_style( 'any-handle', "https://wordpress.stackexchange.com/" );
wp_add_inline_style( 'any-handle', $css );

It feels a bit hacky but the alternative, printing a style tag directly to wp_head, is not good either.