0

I have a custom Wp_Query in my header that displays the latest post and then a list of 10 posts below which are offset so not to include the recent post.

I want to use the latest post's featured image as the background for the header and I've got it working so it displays an image but it's not the recent post's image, it's the next one in the list which I'm guessing is because of the offset.

Here's the code for the custom loop that displays the recent post in the header:

<?php
        $args = array (
            'type' => 'post',
            'posts_per_page' => '1' );
        $featured_post = new WP_Query( $args );
        if ( $featured_post->have_posts() ) {
        while ( $featured_post->have_posts() ) {
            $featured_post->the_post();
            get_template_part('content-home_header',get_post_format());
        }
        } else {
        // no posts found
        }
    wp_reset_postdata();
?>

This is the div tag that pulls in the featured image as the background:

<div class="header-wrap" style="background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url('<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>');">

Essentially I need to display the featured image from the custom loop post but the offset is making it pull in the next post's background image.

Thanks.

1 Answer 1

0

Instead of using the tag outside, you can echo the output inside the post loop.

And no need to add the $post ->ID because WordPress will automatically pick up the thumbnail with the wp_get_attachment_url() function.

2
  • Thank you, although not sure what you mean. The custom post loop is within a div that's nested down a couple of layers down from the main header-wrapper so I need to grab the featured image from within this and use it as the outer div (header-wrapper) background image. Just to clarify, the code I have in place is working in terms of displaying a background image, the problem is, it's showing the wrong post's image as I an offset in the functions file so it's displaying the offset'd post's featured image. I did remove the $post->ID though as you're right it's not needed. Commented Oct 16, 2016 at 14:21
  • The code seems to work perfectly. There is no offset value.While editing the WordPress themes, the cache can be stored. So it would be better if you remove the code and clear the cache. And then add the code. It happens sometimes. The only code which denies to pick up the first post is "offset". But you removed it. So there is no point of showing its output. Just try to clear the cache and then add the code. Commented Oct 18, 2016 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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