I am trying to inject a inline style css to my body element via the functions.php file. It needs to be inline, because I am using a ACF to let the user change the image. This should be the result:
I read about the wp add inline style, but i couldn’t figure it out. Update: Here is the function I tried:
I did load a body.css to tried to add the inline css. But it didn’t work — maybe this isn’t the right approach at all?
I see a couple issues in your sample code. You don’t need the tags, since you’re already parsing PHP. Also, you should be using get_field() since you don’t want to be echo ing the returned value.?php>
3 Answers 3
The easiest way I’ve seen is to echo it where you need it:
Since 2019 you can also add styles inline inside the body , shown here without using echo :
function example_body_open () < ?> html add_action( 'wp_body_open', 'example_body_open' );
The benefit here is you get better syntax highlighting and do not need to escape double-quotes. Note this particular hook will only work with themes implementing wp_body_open hook.
Beat me to it. This is also a «not so eloquent but practical and effective» way to add inline js if needed.
maybe this isn’t the right approach at all?
wp_add_inline_style add extra CSS styles to a registered stylesheet. This function will not add an inline html style to the body tag.
However, I do think this is the correct approach to the problem. You’re basically doing it right, but you need to add both inline css and another class to the body so that the css actually does something.
/** * Conditionally add body class and inline css to body */ //* Add action to wp_loaded to initialize the plugin add_action( 'wp_loaded', 'wpse_106269_wp_loaded' ); function wpse_106269_wp_loaded() < add_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts' ); //* Conditionally add hooks if( '' !== get_theme_mod( 'my-mod', '' ) ) < add_filter( 'body_class', 'wpse_106269_body_class' ); add_action( 'wp_enqueue_scripts', 'wpse_106269_add_inline_style' ); >> //* Make sure we load the custom css. function wpse_106269_enqueue_scripts() < wp_enqueue_style( 'custom-style', '/style.css' ); >//* Add another class to the body tag. function wpse_106269_body_class( $classes ) < $classes[] = 'custom-background-image'; return $classes; >//* Add background-image inline function wpse_106269_add_inline_style() < $background_url = esc_url( get_theme_mod( 'my-mod', '' ) ); $custom_css = ".custom-background-image < background-image:URL( $background_url ); >"; wp_add_inline_style( 'custom-style', $custom_css ); >
You can just use a relative path. For example, if your stylesheet is in /wp-content/themes/mytheme/css/mystyles.css and your image is in /wp-content/themes/mytheme/images/nav-divider.png , then your path would be ../images/nav-divider.png .
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
WordPress is a trademark of the WordPress Foundation, registered in the US and other countries. This site is not affiliated with the WordPress Foundation in any way.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
I’m a newbie to WordPress; I just started learning WordPress. I’m trying to link style.css in functions.php but I am unable to achieve what might be the issue here. Can anyone point me the right direction? index.php
Your index.php appears to be missing get_header() . Your theme needs to have a header.php with the
element in it, and the function inside it.
Jacob — they had the get_header() call in there, it just didn’t show up because the code wasn’t formatted properly. I edited for code formatting (that doesn’t answer whether there’s a header.php or not, though).
4 Answers 4
(1) Your index.php file should begin with:
(2) Your header.php file should have the following right before the closing tag:
Note: header.php also has other things, but I am assuming you have them set up already.
(3) Your footer.php file should have the following right before the closing
tag:
(4) In your functions.php , modify your the second line of your wp_enqueue_style so that it looks like this:
This is because the style.css in your theme folder is the main stylesheet for the theme — so you don’t need to tell WordPress to look for style.css , it will know what to look for.
I have recreated your theme using your code on a local WordPress installation to test it, and here is a screenshot of what I see when I visit the page:
The theme folder has the following files:
And I copied and pasted the exact code for each file from your original question, with one exception: for functions.php I added the starting
When people are asked about features they would like to CSS, “variables” always seems to come up. Whether or not this is a good idea is still something I personally haven’t decided on, but I’d lean toward yes. Regardless, using PHP, it is trivially easy to use variables in CSS. This is certainly not a new trick, but I’ve never specifically covered it so I thought I ought to.
Below all that PHP stuff, you can just commence regular CSS writing, only you can intermix some PHP to spit out those variables.
#header < background: url("/images/header-bg.png") no-repeat; > a < color: ; > . ul#main-nav li a < color: ; >
Extend the power / Other ideas
While you are at it, might as well compress the CSS with PHP.
Theoretically you could pull the user agent and attempt to do browser-specific CSS, but that is littered with problems and not recommended.
Pull the date/time, and perhaps change some stuff on your site for the different seasons or time of day.
Generate a random number, test the result, use it to set a random background image on your header.
I did a totally static test page and it worked fine, then I tried this same technique within a WordPress site and no dice. The solution for me was to leave the file named style.css, and use .htaccess to parse it as PHP. Just make sure this code is in the .htaccess file (Apache servers only) at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.
Carlo DeAgazio wrote in to say this works for him in WordPress:
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
Hey Chris, I was playing with this idea the other day, but never had time to look deep into it. I have one question: what can you tell me about perfomance? I suppose it´s slower than a pure css stylesheet, but it´s much slower or you cant even notice the difference? Thanks for your time and for this very interesting post.
Really interesting concept. I could see it being very useful in a corporate setting like where I work now. It would be easy to change colors/fonts if the corporate branding went in a new direction.
@Martin There’s no reason why it should be slower than pure css: The moment the css is delivered to the client from the server, it has become pure css already. Don’t forget that any php code is executed on the server before anything happens in the browser. If your code is really complex, you might notice some kind of downside on performances because it would take some time for the server to execute the script. However I don’t see this happening at all with this kind of method. My 2¢
I’m sure there is some cost as the server has to process it and then deliver it, rather than just deliver it – but we’re talking microseconds here. When I used this method, it wasn’t noticeably slower than pure CSS.
Thanks for your answers, both O and LineIn. What you´ve wrote seems very coherent, so I think its just a matter of give this a try!
There is actually a performance issue. As far as I know, these php-parsed stylesheets do not get cached by the client. So the stylesheet is processed everytime it is called by the client. Correct me if I am wrong. You could probably set an “expires” header in php but I’m not that into HTTP myself. Any ideas?
Actually you don’t need to work around the caching problem. Since you aren’t really doing anything dynamic inside the script you could just run the following from the command line on mac/linux: php myStyles.php > myStyles.css Then link the the css file we just generated. You’ll have to recompile the css file each time you change it, so it’s only really useful once you’re done testing.
There are some major performance issues. You should not use PHP or any application tier logic to generate static content at runtime. I go into all the performance issues here: http://bit.ly/4suKSp
Another way to do this, albeit not very effective, is to embed the styles directly in document and have php echo the variables there. A more useful variant of this method is applying it to JavaScript. I once utilized this when I had to position an element with JS generated CSS, when the position was reliant upon the submitting of a php form.
The biggest reason I’d want to use CSS Variables is class inheritance. e.g. for sprites. .sprite < background-url… text-indent… > .header extends .sprite .header < background-position… > .submit extends .sprite .submit < background-position… > Which saves us from having to put things like input submit” and littering HTML with class names. I’d love to see something like that using this method. Nicole Sullivan goes into some depth about this here: http://www.stubbornella.org/content/2009/11/09/css-wish-list/
you should take a look at the github project page of oocss (http://github.com/stubbornella/oocss) . there you can find a lot of object oriented css code, which can be used like this “input submit” ” . everybody knows that this is not the best way to do it but it’s actually a concept that should find it’s way into the css specs. of course the project is open to any kind of contributions (ideas, comments, code, …)
Well, there is an ‘Object Oriented CSS’ out there but am not sure if it allows inheritance.. (though I believe it should) Have to study it.. Darn, these technologies are developing at a very past pace… No sooner I learnt CSS 2.0 than new versions of CSS i.e. CSS 3.0 and Object Oriented CSS came out in the market 😛
You could also use something like Scaffold to do this, which also adds a number of other benefits (caching, nested selectors, compression, etc.).
Scaffold would be what I’d use if I were to go down this route. I’ve tried it out but unfortunately it doesn’t work on my WAMP set-up.
Chris, Since you’re the WordPress pro, I thought I’d ask. Is there an easy way to work this into a WordPress theme? A lot of times when I sell a theme I get requests to change colors, etc, by people who don’t know CSS. If all they had to do was change a few variables at the top then it would be easy to explain.
I’ve always been perplexed by why this enhancement is so desired because this functionality already exists. Don’t you have have the ability to have psuedo variables with the ability of specifying multiple classes?
That means you’d have to define style in the HTML. I’m not going to explain why that’s bad, google knows 😉
This is exactly what I was going to post. I found it very liberating to quickly create divs say div h200px float-l bgcolor1 textcolor3 font1″ I don’t see why this is any worse or heavier than giving an element an id and creating a style chunk for it when I was playing around with this I was able to do a lot more with less code since you can declare a bunch of design specific variables and then just apply them to whatever element you desire easily. It also sets up addClass and toggleClass well with jQuery. I would like to know the downsides to this method though. Obviously when working with dynamically generated content things could get stickier. I noticed facebook uses a lot of these descriptor classes in their markup.
The WordPress theme Mandigo uses this technique. The style sheet is style.css.php. Interesting theme, but this makes it difficult to modify the theme at the code level. The end user has quite a bit of control using the admin theme options.
ohhh. interesting. that would be a big draw if users could set color codes in an admin panel I think.