简体   繁体   中英

making a background image dynamic in wordpress

I am trying to get my background image dynamic in wordpress. My goal is to have the user to be able to change the background image through wordpress dashboard. I am using Advanced Custom Field plugin.

I've read through Advanced Custom Field website but couldn't find anything on background images on it.

Sample code will be helpful.

Thank you

ACF does not provide separate field for the background image but you can use the simple image filed and use it to set your background image.

for that define an image field from ACF menu. and paste this code in your page where you want to put the background image

<div style="background-image: url(<?php echo get_field('background'); ?>);"><div>

as you can see you can use css property background-image to set the background image here it will fetch the image stored in 'background' field and put it as an background image.

PS:- you have to replace fieldname 'background' with your field name.

you can output dynamic styles in the header of your page by using the wp_head hook. here is an example (add this in your functions.php):

function my_inline_styles() {
    $body_bg_image="/wp-content/uploads/myimg.jpg"; //here you would get your value from ACF
    ?>
<!-- start my dynamic styles-->
<style type="text/css">
    body {background-image: url('<?= $body_bg_image ?>')};
</style>
<!-- end my dynamic styles-->
    <?php
}
add_action('wp_head', 'my_inline_styles');

i would recommend sticking them into the header instead of the footer, to ensure early loading of these styles.

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