1

I have wordpress theme and I want to add custom css

So I try to add to header

<style>
<?php if (!empty($btn_color)){  ?> 
.btn-default{ background-color:<?php echo esc_attr($btn_color);?>; } <?php } ?>
</style>

But it seems it isn't good way and I need to use

wp_add_inline_style() 

So how to use this function?

2

According to Codex, this function accepts 2 arguments:

<?php wp_add_inline_style( $handle, $data ); ?>

Take a look at this example:

function my_inline_css() {
    wp_enqueue_style(
        'custom-style',
        get_template_directory_uri() . '/css/custom_script.css'
    );
        $btn_color = esc_attr( get_theme_mod( 'my-custom-color' ) ); 
        $custom_css = "
                .btn-default{
                        background-color: {$btn_color};
                }";
        wp_add_inline_style( 'custom-style', $my_custom_css );
}
add_action( 'wp_enqueue_scripts', 'my_inline_css' );

You should have an option in your theme to specify the background-color and then output it using wp_add_inline_style().

You also have other options, such as hooking into wp_head():

function my_inline_css($btn_color) { 
    if ( !empty($btn_color) ) {  ?> 
        .btn-default { background-color:<?php echo esc_attr($btn_color);?>; } <?php
    }
}
add_action('wp_head','my_inline_css');

However i don't know where that $btn_color value is set. You might want to add this information to your question to be able to get an accurate answer.

1
  • I would note that in this case $btn_color should be escaped
    – Tom J Nowell
    Apr 14 '17 at 19:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.