Question: Dynamically change the background image in CSS for different posts in wordpress

Question

Dynamically change the background image in CSS for different posts in wordpress

Answers 3
Added at 2017-01-05 12:01
Tags
Question

Is it possible to change the background image called in CSS dynamically for different posts? In short, I am looking to show the featured image of a post in WordPress as background?

background: #253340 url('assets/images/blog/post-2.jpg') no-repeat 50% top;

I did try this one find on this forum but didn't work.

background: #253340 url(<?php echo $variable_holding_img_url; ?>) no-repeat 50% top;
Answers
nr: #1 dodano: 2017-01-05 12:01

If your theme supports post thumbnails you can do the following as long as the css code is in the template and not in a seperated css file

<?php if (has_post_thumbnail( $post->ID ) ): ?>
    <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
    <div id="custom-bg" style="background: #253340 url('<?= $image[0] ?>') no-repeat 50% top;')">

    </div>
<?php endif; ?>
nr: #2 dodano: 2017-01-05 13:01
<?php
$image_url = 'my_default_image_url.jpg'; // fallback image url

if ( has_post_thumbnail() ) {
    $post_thumbnail_id = get_post_thumbnail_id();
    $image_url = wp_get_attachment_image_src( $post_thumbnail_id, 'large' )[0]; // large or full or custom size
}
?>

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

Function References

nr: #3 dodano: 2017-01-05 13:01

No, above code will break your work as it will return all exact image tag and data. You should use like this way.

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ));
<!-- div that holds the background -->
<div style="background: #253340 url('<?php echo $image_url[0]; ?>') no-repeat 50% top;">
    <!-- some other content -->
</div>

And it will produce exact out put.

Note: this code will go inside php file not in your css file.

Source Show
◀ Wstecz