Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I was wondering if it's possible to enqueue raw CSS as a string directly from within a template file?

I'm writing a custom template for a page and need to add some style rules for it. What I want to do is write the styles out as a string var in PHP then use the enqueue_style function to load these styles, rather than me having to add them in to 'style.css' or some other external style-sheet.

I assumed that so long as I enqueue my styles before calling the 'get_header' function, and if I hook in to the 'wp_head' or 'wp_enqueue_styles' actions, that this would work but it doesn't appear to and I'm not sure if 'wp_enqueue_style' can take a raw CSS string.

Anyone got any advice please?

Kind regards,

Chris

share|improve this question

3 Answers 3

up vote 4 down vote accepted

Yes and no.

You can load a raw CSS string into the header programatically, but you can't use wp_enqueue_style() to enqueue it. That function specifically loads files into the header in <link> tags.

But what you can do is something like this:

function print_inline_script() {
?>
<style type="text/css">
/* ... styles go here ... */
</style>
<?php
}
add_action( 'wp_head', 'print_inline_script' );
share|improve this answer
    
Superb! That'll do me just fine, thanks EAMann! –  Chris Jun 25 '12 at 20:57
    
Great thinkin'. –  Cameron Hurd May 21 at 0:51

Yes as long as it's registered/enqueued before wp_head() in the header.

share|improve this answer

Sorry, I just noticed this bit:

I assumed that so long as I enqueue my styles before calling the 'get_header' function, and if I hook in to the 'wp_head' or 'wp_enqueue_styles' actions, that this would work but it doesn't appear to and I'm not sure if 'wp_enqueue_style' can take a raw CSS string.

It should be working, make sure you've entered both a handle and a URL for your CSS file.

share|improve this answer
1  
Thanks but there is no 'CSS file' I want to enqueue a string variable containing the CSS rules, as I said in the question. Do you know if this is possible? –  Chris Jun 25 '12 at 20:02
1  
as a side note: I believe that it's preferable on here for you to 'edit' your previous answer if you need to change it rather then post a second (unless of course it's an entirely different answer). just fyi –  Chris Jun 25 '12 at 20:04
    
I'm sorry to welcome you with a downvote, but please read the full FAQ of this site... –  brasofilo Jun 26 '12 at 3:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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