0

In a WordPress theme I have a custom function that generates some HTML and CSS based on factors on the page. Previously I had simply dumped the generated CSS into embedded <style> tags. However, as this is breaking W3C validation, I'd like to find a way to maintain the flexibility of calling the function in the theme files (page.php, single.php, etc.), but have the generated CSS be outputted in the <HEAD> tag.

I understand wp_add_inline_style() can enqueue inline styles, but I'm unable to see how this could work in my above described situation. Any help is much appreciated.

3
  • Can you use the wp_head() hook?
    – Howdy_McGee
    Apr 25, 2016 at 21:04
  • share your code details when you are using wp_add_inline_style Apr 26, 2016 at 6:10
  • I'm not using it, so there's no code to share. The question is, can I use it? The important thing is that the CSS be generated dynamically via a function call in a template file (like single.php or page.php) but then be output in the HEAD (I believe by wp_add_inline_style)
    – Ryan
    Apr 30, 2016 at 0:45

1 Answer 1

0

If you use wp_enqueue_style(), with your function, you could call the function from the page (single.php etc.) ... pass a string through with the page name, use that in the function to decide which style you are enqueuing. This will then load the script in the head in the correct manner.

https://developer.wordpress.org/reference/functions/wp_enqueue_style/

Eg.

// In single.php
enqueue_my_script('single');

//In functions.php
function enqueue_my_script($page = null){
    if($page === 'single') {
         add_action( 'wp_enqueue_scripts', 'single_styles');
    }
 }

 function single_styles() {
      wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css', array(), null, null);
 }

I'm pretty sure something like that should work how you want it to, though it is nearly 2am for me!

1
  • This looks promising, but as it's laid out now could only enqueue a static CSS file. If there's a way to pass single_styles a variable (i.e. a string of inline CSS), then wp_enqueue_style could be changed to wp_add_inline_style.
    – Ryan
    Apr 30, 2016 at 0:43

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.