How to stop featured image thumbnail [set as background image] on blog index page just repeating same image across all posts

How to stop featured image thumbnail [set as background image] on blog index page just repeating same image across all posts:

i have this code here:

add_action( 'wp_head', 'set_featured_background', 99);
function set_featured_background() {
    if ( has_post_thumbnail() ) { 
        $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
        ?
        style
        .has-post-thumbnail {
            background-image: url('?php echo $featured_img_url ?');
            background-size: 100% 100%; 
        }
        /style
        ?php
    }
}

And ive tried a few different variations but it always jsut finds the most recent posts image and uses that across all posts. Do i need to be trying to put in a check to make sure it does the same thing every unique post. For example: If this post has a unique ID find its thumbnail image and apply as a style. Or is it because im trying to add it to the css class has-post-thumbnail which is applied to all posts? [that have a thumbnail]

Topic blog-page post-thumbnails php css Wordpress

Category Web


I would try to use the ID of the post (which should be part of the id or class of the article-tag) as additional selector for the style:

<style>
    #post-<?php the_ID();?>.has-post-thumbnail {
        background-image: url('<?php echo $featured_img_url ?>');
        background-size: 100% 100%; 
    }
</style>
    

Or is it because im trying to add it to the css class .has-post-thumbnail which is applied to all posts?

Yes, set_featured_background() gets first post from the loop and add .has-post-thumbnail to styles. All posts that have thumbnail (with class .has-post-thumbnail) will have the same background.

Try setting the background in the template file responsible for displaying posts on the home page, probably in content.php or front-page.php.

<?php
    $attr_style= '';
    if ( is_home() && has_post_thumbnail() ) {
        $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
        $attr_style = ' style="background: url('. $url.'); background-size: 100% 100%;" ';
    }
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); echo $attr_style; ?>>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.