简体   繁体   中英

Wordpress - background image not working with home_url()

I have a number of background images I'm using on a WordPress site which is ready to move to production. I'm changing all the localhost absolute links in my style.css file. I've changed my code for a background image from this:

background: url('http://localhost:8888/wp-content/uploads/2017/07/homepagemain.jpg') center center no-repeat;

To this:

 background: url('<?php echo home_url(); ?>/wp-content/uploads/2017/07/homepagemain.jpg') center center no-repeat;

When I do this the image doesn't show up, not sure if I'm just using the wrong function but this works on my img links in my html. How can I fix this? Do I need to use get_the_post_thumbnail_url() to move the image edit into the admin area and away from the stylesheets? Any assistance appreciated.

use below code in template. because php code does not works in css file. so you must use in php file

<?php
$uploads = wp_upload_dir();
$upload_path = $uploads['baseurl']; // now how to get just the directory name?
?>

<div style="background: url('<?php echo esc_url($upload_path); ?>/2017/07/homepagemain.jpg') center center no-repeat;"></div>

I don't know why the other answers are making such a simple problem, so complex.

All you need to do is remove http://localhost:8888 from the image path, thus creating a relative link and it will work fine.

You also get the added benefit of it working on http and https protocols if you decide to change in future. All you need is:

background: url('/wp-content/uploads/2017/07/homepagemain.jpg') center center no-repeat;

将图像保存在图像文件夹中,并在模板中使用以下代码:

<div style="background: url('<?php bloginfo('template_url'); ?>/images/homepagemain.jpg') center center no-repeat;"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM