posts - get_the_excerpt() is not working as expected - returns wrong text

admin2025-06-03  2

In my template's 'footer.php', I'm attempting to generate a list of the four most recent blog posts, showing the featured image, title, excerpt, and a link to view.

The title, featured image, and URL are correctly generated, but the function get_the_excerpt($post_id) is returning unexpected results.

Sometimes, it returns the correct text excerpted from the blog post. Other times (i.e. upon refresh), it returns an excerpt from the first page of the site, not even a blog post.

Here's a screenshot:

Dumping the $rp variable shows the correct posts are returned. I'm using setup_postdata() per this page.

Am I using get_the_excerpt() incorrectly?

Note that the posts don't have manually-defined excerpts. I'm simply trying to get an auto-generated excerpt of each post.

Here's the code:

<!-- Recent posts -->
        <div class="recent-posts row">
            <?php 
            // Get list of recent posts:
            $rp = wp_get_recent_posts([
                'numberposts' => 4          
            ]);
            var_export($rp);

            foreach($rp as $p) : 
                global $post;
                $post = $p;
                setup_postdata($post);
                ?>
                <div class="col-sm-3">
                    <div class="card" width=>
                        <img class="card-img-top" src="<?=get_the_post_thumbnail_url( $p['ID']) ?>" alt="<?=$p['post_title'] ?>">
                        <div class="card-body">
                            <h5 class="card-title"><a href="<?=get_permalink( $p['ID'] ) ?>"><?=$p['post_title'] ?></a></h5>
                            <p class="card-text"><?=get_the_excerpt( $p['ID'] )?></p>
                            <a href="<?=get_permalink( $p['ID']) ?>">Read full post</a>
                        </div>
                    </div>
                </div>
            <?php
            endforeach;
            wp_reset_query();
            ?>
        </div> <!-- end recent-posts -->

UPDATE: So I got this to work, thanks to @SallyCJ in the comments below. Here's how:

When iterating through the posts returned by wp_get_recent_posts(), each post needs to be retrieved as an object and assigned to the global $post variable:

// (inside loop)
global $post;
$post = get_post($p['ID'], OBJECT);  // Retrieve the post as an object.
// NOW `get_the_excerpt()` works properly. 

NOTE that there appears to be a bug in get_the_excerpt, as it completely ignores any argument passed in. I can pass any post ID, and it always returns an excerpt for the current post.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748939518a314996.html

最新回复(0)