简体   繁体   中英

Solution to set background-image using [shortcode]?

  • I'd like to set a random background-image into a <div> Container </div>
    • To keep it simple I installed a plugin using [shortcode] to display random images. This works fine.
    • How to get the shortcode [wp-image-refresh] working together with background-image:url(...)
    • I tried it even as inline-style with no result.

This is what I have:

HTML

<div class="header_random-image">
   <div id="hero"></div>
</div>

CSS

#hero {
  background-image: url('<?php echo do_shortcode("[wp-image-refresh]"); ?>');
  background-size: cover;
  background-position: 50% 30%;
  height:70vh;
  width: 100%;
  margin-top: -65px;
}

Another try with no result: Inline-style

<div class="header_random-image">
        <div style="background-image: url('<?php echo do_shortcode("[wp-image-refresh]"); ?>')"></div>
</div>

Could anybody be so kind to help? Or does anybody has a simple solution to place div-random-background-images?

Best from Berlin

In most cases your CSS code will be served in a static file, thus the php code won't execute.

As the inline example doesn't work either, I guess the short code does not return an image url but a full image tag instead. The plugin's description confirms this assumption. WP-IMAGE-REFRESH

You could try this:

PHP

<div class="header_random-image">
   <?php echo do_shortcode("[wp-image-refresh class='hero_class']"); ?>
</div>

CSS

.header_random-image {
  overflow: hidden;
}
.hero_class {
  height: 100%;
  width: auto;
  margin-top: 0;
}

This should display the image. You'd still have to center it if you want (use flex-box) and check for problems caused on different screen sizes depending on the side ratio of your uploaded images and solve them with some Javascript.

Alternative

Use ACF Pro and add a gallery field to your posts/pages or an option page if you want the same images on all views.

PHP

<?php 
    $images = get_field('name-of-your-gallery-field');
    shuffle($images);
    $imageUrl = images[0]['url'];
<div class="header_random-image">
    <div style="background-image: url('<?= $imageUrl ?>"); ?>')"></div>
</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