How to add dynamic css to WordPress with wp_add_inline_style

As you start to develop sites, you’ll find yourself wanting to add CSS to your sites that is based on some sort of dynamic value, which could include user input, such at theme color pickers, or post/term meta…

You could create a PHP-driven CSS file, but this is quite heavy and slow for your site. Since WordPress 3.3, there’s been a better way to add this to your site, though it isn’t talked about much.

wp_add_inline_style() allows you to add extra CSS rules directly inline after an enqueued CSS file has been loaded. This means that after your enqueued CSS file is called, inline CSS using the HTML

<style>

tags will be added immediately afterwards. This provides several benefits including being able to override styles in your enqueued stylesheet if you have any custom values set.

IMPLEMENTATION
The usage of wp_add_inline_style() is really quite simple. All you need to provide is the handle of the stylesheet you want to add the CSS to and then the CSS declarations themselves.

Recall that when you register or enqueue a CSS file, you need to provide a “handle”, or reference name. In the enqueue example below, parent-style is the handle.

function scripts_loader() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/main.css', array(), null );
}
add_action( 'wp_enqueue_scripts'   , 'scripts_loader');

So if you wanted to add some dynamic styles to that CSS file, wp_add_inline_style() will add them inline after the CSS is loaded. To do so, you could do something like this:

<?php
$button_border_radius= 3px;
$custom_styles = '';

$custom_styles .='
.btn.btn-primary {border-radius: '.$button_border_radius.'px ; } 
';
if ( $custom_styles != '' ) {
  $css = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $custom_styles);
	wp_add_inline_style( 'parent-style', $css );
}
?>

Example:

function print_embed_style(){
        $style = get_embed_style();

        $style = preg_replace('#/\*.*?\*/#s', '', $style);
        $style = preg_replace('/\s*([{}|:;,])\s+/', '$1', $style);
        $style = preg_replace('/\s\s+(.*)/', '$1', $style);

       //TODO Fix this hack? naming z_ to make this css final
        wp_register_style('z_front_style', false);
        wp_enqueue_style('z_front_style');
        wp_add_inline_style('z_front_style', $style);
}
function get_embed_style(){        
        
        $header_bg_img = get_theme_mod( 'header_bg_img', '' );         
        
		$css = "";

        if($header_bg_img){
            $css .='
                .header-page {background-image: url('.esc_url( $header_bg_img ).'); } 
            ';
        }	

        return $css;		
}

add_action( 'wp_enqueue_scripts','print_embed_style', 9999);