简体   繁体   中英

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: http://i.stack.imgur.com/5C58t.png

And that's the content of my post on which the footer is displayed: http://i.stack.imgur.com/R6ok7.png

Do you have any idea why is that happening guys?

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM