6

I am trying to get my head round the wp_add_inline_style() function in WordPress.

//setting inline css.
function my_styles_method() {
    wp_enqueue_style(
        'custom-style',
        get_template_directory_uri() . '/css/custom_script.css'
    );
        $color = get_theme_mod( 'my-custom-color' ); //E.g. #FF0000
        $custom_css = "
                .mycolor{
                        background: {$color};
                }";
        wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method' );

I understand most of it but I am not understanding this bit:

wp_enqueue_style(
   'custom-style',
    get_template_directory_uri() . '/css/custom_script.css'
);

Is this a dependency? or a blank css file so that code is written to it?

If its dependant then why? I just want to load custom css into the theme so it can be more customisable.

Thanks

6

wp_add_inline_style() is intended to add additional CSS to an existing stylesheet. The idea is that you may need to dynamically alter the stylesheet - for instance, you have user-selected colours associated with categories and you would like to colour each category's title accordingly. You can't hardcode this since the colours in question are not known, but live in the database.

So

wp_enqueue_style(
   'custom-style',
    get_template_directory_uri() . '/css/custom_script.css'
);

is just queueing an existing stylesheet to which we'll attach our dynamically generated CSS.

It seems what you're trying to do is is load user-entered CSS. I wouldn't really recommend this - offering tweaks via the customiser is a good way of allowing users to personalise the theme, but if they need to make substantial changes, what they're really after is a child theme.

However, if you are to do this, I would use wp_enqueue_style() to load the theme's style.css and then attach customisations to that. (Most themes seme to hard-code the style.css into the <head>, but I don't know hwy).


Developers: You should be aware of this trac ticket: http://core.trac.wordpress.org/ticket/24813

| improve this answer | |
  • that bug has since been closed. – pcarvalho May 15 '14 at 20:26

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.