Michał Kostrzyński
Michał Kostrzyński

Reputation: 373

Wordpress - posts displayed in loop in post have the same the_excerpt() output

I've encountered a problem, which is quite annoying. The thing is that I've two loops in my footer which are loading 3 last posts from two different categories. It looks like that:

<?php $posts = get_posts('category=21&orderby=desc&numberposts=3'); foreach($posts as $post) { ?>
    <div class="footer-text-block">
        <a href="<?php the_permalink() ?>" target="_parent">
            <span class="footer-white-bold"><?php the_title(); ?></span>
        </a><br />
        <span class="footer-grey-thick"><?php the_excerpt(); ?></span>
    </div>
<?php } ?>
<?php $posts = get_posts('category=22&orderby=desc&numberposts=3'); 
      foreach($posts as $post) { ?>
    <div class="footer-text-block">
        <a href="<?php the_permalink() ?>" target="_parent">
            <span class="footer-white-bold"><?php the_title(); ?></span>
        </a><br />
        <span class="footer-grey-thick"><?php the_excerpt(); ?></span>
    </div>
<?php } ?>

And what it outputs is that: https://i.sstatic.net/5C58t.png

And that's the content of my post on which the footer is displayed: https://i.sstatic.net/R6ok7.png

Do you have any idea why is that happening guys?

Upvotes: 1

Views: 906

Answers (2)

Pieter Goosen
Pieter Goosen

Reputation: 9941

You have a couple of issues here

  • You need to reset your postdata after every custom query, that is after every instance of get_posts(). You can simply add wp_reset_postdata(); after every end of your foreach loop

  • you have a couple of foreach loops which uses the same $post value. You have to remember, the last value exists outside your foreach loop, and if it is not destroyed, it will influence the value in the next foreach loop if it has the same name. You can either rename the value to be unique for each foreach loop, or you can just use unset($post) after/outside your foreach loop.

  • You need to set up postdata before you can make use of template tags like the_excerpt() or the_title(). Simply add setup_postdata($post); right after you started your foreach loop

Upvotes: 1

Mars
Mars

Reputation: 1

Try using setup_postdata($post); to make all post-related data available. You need:

foreach($posts as $post) {
    setup_postdata($post);
    // the rest of your code
}

setup_postdata()

Upvotes: 0

Related Questions