简体   繁体   中英

Access background image in Wordpress

I'm currently turning a HTML page into a WordPress theme. Throughout the site I have a series of divs that use CSS backgrounds. What is the best practice for linking those images, so the user can change them as they please?

For reference, in the HTML, I have: background-image:url(/site/sprite.png);

You can use custom fields. If you don't know how to make them or you want an easy and robust way to manage them you can find the "Advanced Custom Fields" plugin in the wordpress.org plugin repository. It's free and it's very nice.

The way you would use custom fields here is because you will set those backgrounds with inline style to your theme. Otherwise "the user" will have to know how to change a CSS line of code (not very practical).

If you set them inline they would look something like this:

<div id="divBackground01" style="background: url(<?php echo get_post_meta('$post->ID','div-bg-01',true); ?>);>

</div>

Another option that I've seen people do is make the CSS file in a PHP file... you would use something like:

<style>
  #divBackground01 {
    background: url(<?php echo get_post_meta('$post->ID','div-bg-01',true); ?>);
  }
</style>

Note that it's using PHP because the file would actually be a PHP file... otherwise you can't use PHP in a CSS file. Not sure that it's a very good practice to do this, but it's something doable as another option if you want.

Best to stick with adding the background style inline with the custom field. You can use PHP to make it conditional if needed and you can probably setup 1 post (so you have single ID) with all the custom fields... or whatever way you would prefer to present it to the user is your choice.

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