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');
        .has-post-thumbnail {
            background-image: url('<?php echo $featured_img_url ?>');
            background-size: 100% 100%; 

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]


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.

    $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; ?>>
  • even if i take set_featured_background() out, it still repeats. Issue is im trying to do it without basically writing a whole new blog loop, but from what i can tell it looks like im going to have to do that so i can inline style this one bit. – Moose Aug 21 '18 at 8:39
  • Is the site preview somewhere available? @Moose – nmr Aug 21 '18 at 8:44
  • if you inspect the img inside the entrycontent, and untick display none, you will see what its supposed to look like – Moose Aug 21 '18 at 8:56
  • Why is display: none set there, if you want the image to be visible? Do you want to remove this from background? @Moose – nmr Aug 21 '18 at 9:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.