Add inline CSS style to existing WordPress Plugin or Theme

WordPress facilitates the use of injecting inline CSS to an existing plugin or themes’ CSS via a function called wp_add_inline_style. This avoids echoing out a bunch of CSS using wp_head and is considered better practice.

One of the beneficial reasons is that it only appears where the existing plugin or themes CSS appears, that is, it may not be sitewide, also it immediately follows the main stylesheet so the CSS load order is better managed in terms of specificity.


In the image above a plugins main CSS file is loaded with an id of slicknavcss-css, a second stylesheet follows slicknavcss-inline-css, which are user generated CSS options from the plugin settings that need to load as CSS values, such as menu color, font-size etc – since these settings are an unknown they need to be passed in after the plugin is loaded and the settings are saved.

So as in above I have created a function wpb_add_inline_css and a variable $slicknav_custom_css to which I have made its value all the user generated rules, note that the variable is surrounded by double quotes to preserve the variables it is pulling from the database.

Then I am adding that the variable into the main CSS id of the stylesheet that already exists with a handle of slicknavcss using the wp_add_inline_style function.

Finally the main function is enqueued with wp_enqueue_script and ready to load.

Still Not Loading…

I have found that sometimes you need to enqueue the target CSS stylesheet if the inline style is not loading – so in the above the only difference is that the target CSS style sheet is also enqueued.

The same principle applies to themes as the author may allow users to apply certain CSS styles after the theme has been activated.