Using wp_add_inline_style without a stylesheet

The question:

I need to add custom inline styles to the header of a custom theme I’m creating. I’ve come across the wp_add_inline_style() function, which works but doesn’t really suit me as it depends of a specific stylesheet. I’d need to add inline styles at the end of the head tag without a stylesheet dependency.

I’ve tried to set either the theme stylesheet or a non-existent one. In both cases, it works but it’s a bit of a dirty hack IMO (either load the theme stylesheet twice or refer to a ghost file…). Is there a proper way to add inline styles in head without depending of a stylesheet?

Of course, I could add them directly in the header.php file but I’d like to avoid this.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You just need to add the styles directly to the page head. The best way to do this is to use the ‘wp_head’ action hook, assuming you are using a theme that has the hook. Like so:

add_action('wp_head', 'my_custom_styles', 100);

function my_custom_styles()
{
 echo "<style>*{color: red}</style>";
}

Check out the WP codex to learn more about action hooks.

Method 2

You could simply use a “dummy” handle:

wp_register_style( 'dummy-handle', false );
wp_enqueue_style( 'dummy-handle' );

wp_add_inline_style( 'dummy-handle', '* { color: red; }' );

Method 3

Your theme most certainly has a default stylesheet (otherwise it wouldn’t it even be loaded as a theme).
Just use this very stylesheet as the handler for your inline CSS. An example can be found in the functions.php of the theme TwentyFifteen (code skipped for brevity):

function twentyfifteen_scripts() {
    wp_enqueue_style( 'twentyfifteen-style', get_stylesheet_uri() );

}
function twentyfifteen_post_nav_background() {
    wp_add_inline_style( 'twentyfifteen-style', $css );
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment