WordPress – adding dynamic styles with wp_add_inline_style

I’m trying to wrap my head around the wp_add_inline_style function in WordPress.

I’ve managed to output my customiser CSS using this function and it works perfectly.

Here’s how I am using the wp_add_inline_style function to output the customiser styles;

function theme_custom_css() {

    $header_height = get_theme_mod( 'header_height', '96' );

    $output .= '.site-header { height: ' . esc_attr( $header_height ) . 'px; };

    if ( ! empty( $output ) ) {
        wp_add_inline_style( 'custom-style', $output );

add_action( 'wp_enqueue_scripts', 'theme_custom_css' );

This works exactly as expected. It adds a style tag to the head below the style.css file with all the custom css inside. Great, that’s exactly what I wanted.

However, if I have another file where there is CSS that can be changed by the user and I want to add the changed CSS to the style tag printed by the wp_add_inline_style function. This doesn’t work. Here’s the code where I’m attempting this.

function theme_slider_css() {

    if ( get_field( 'slider_padding_top' ) ) {
        $slider_css .= '.slider-inner-wrap { padding-top: ' . get_field( 'padding_top' ) . ';px }';

    if ( ! empty( $slider_css ) ) {                                         
        wp_add_inline_style( 'custom-style', $slider_css );

add_action( 'wp_enqueue_scripts', 'theme_slider_css' );

The theme_slider_css function is being completely ignored.

Am I completely missing the point here? Is there anything obvious I am missing?

I would be happy to have two separate style tags printed in the head but I cannot achieve that either?

Hopefully I’ve explained this well, if not, please ask.

Any help will be appreciated.

Thank you in advance.

Read more here: WordPress – adding dynamic styles with wp_add_inline_style

Leave a Reply

Your email address will not be published. Required fields are marked *