简体   繁体   中英

I want to add background image in WordPress in CSS

My html

<section class="banner-area">
    <div class="container">
      <h1>Home</h1>
    </div>
</section>

My css

.banner-area {
  position: relative;
  background: #f0fffa;
  padding: 30px 0;
}

I want to add background image here.

.banner-area:before {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  content: "";
  background: url(../images/bg03.png) no-repeat;
  background-size: cover;
}

I think PHP code cannot run in CSS. How can I do this?

Assuming your CSS file is located within the WordPress directory somewhere, for example in wp-content/themes/foobar/example.css , rename the file to wp-content/themes/foobar/example.css.php (append a .php extension!) and prepend the following code to the beginning of the file:

<?php

header('Content-Type: text/css; charset=utf-8');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');

$pathToBackgroundImage = '../images/bg03.png'; // <- get image path dynamically
?>

Now you in fact can execute PHP within the CSS file, while for the browser the output will be CSS due to the Content-Type.

If you don't need the WordPress API to get your background image path, you can omit the require_once line. However, if you need to query WP media, it might be good to have it there. Now you have access to all of WP's functionality as well as being able to dynamically insert the path:

.banner-area:before {

  left: 0;
  content: "";
  background: url(<?= $pathToBackgroundImage ?>) no-repeat;
}

Then, change the source path to your CSS-file to: wp-content/themes/foobar/example.css.php .

I solved this issue. This is best and easy solution

<div style="background: url('<?php echo get_template_directory_uri();?>/img/bg03.png')no-repeat;background-size: cover;">

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