Correct path to wp-content using php

Stumped a bit here… ( probably a newbie question )

Why does this not work in the css file:

    background-image: url("<?php echo "{$_SERVER['SERVER_NAME']}";  ?>/catering/wp-content/uploads/2017/06/hat.png");

Whereas if I use a direct path, like this, it does…?

    background-image: url('https://sitename.com/catering/wp-content/uploads/2017/06/hat.png');

The reasoning is that when the site gets moved to anotther server - as it will, then using the php string will automatically use the servers name

That way I dont have to go into the css and change every instance of an img being used by the css - it should update itself to match to the new domain

Have I set this up wrong? is the idea sound?

although somehow using the php, along with some way to see if its in a sub dir is even better… then it would simply work no matter where the dir was located…

Not a WP expert, but I presume the server has the usual configuration whereby only php files (with a .php extension) are paresed as PHP, therefore a CSS file will not parse as PHP, unless you configure the server to do so.

Are you moving server, or to a different domain? That path contains a domain name, not a server name. If the domain is the same, no problem.

But why use an absolute path? A relative path should work with any domain, with the same directory structure.

That sounds like bad css design. If that same background is used by multiple classes, enough to make editing them all too much of a task; perhaps there should be a single class for that background.

1 Like

Hey ,
If you want to add background image by css you can do one alternate option is that create image folder in that you can put all images you want to use in background and add that path in ulr(“”).

For Ex.
background-image: url(“images/hat.png”);

OR
If you want to use from the wp-content/uploads folder you can directly access it

For Ex.
background-image: url(“…/…/uploads/2017/06/hat.png”);

So if you move website to another server you don’t need to change any server name.

I used harshal2’s reply - it wasn’t that the css was badly formatted, it was the case that PHP did not work in there.
Thanks for the assist.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.