WordPress query. Correctly referencing the excerpt for a page?

Stuck with a WordPress query…
It’s proably obvious what i’m trying to do…. But one line i just can’t work out, and can’t find any online info about it…

I’ve marked the excerpt line of code which i believe is causing the problems. What would be the correct reference for the excerpt?

Read More
$posts = get_posts(array(
'numberposts' => 2,
'post_type' => 'page',
'meta_key' => 'front_page_feature',
'meta_value' => '1'
));

if($posts)
{
echo '<ul>';

foreach($posts as $post)
{
    echo '<li><article><a href="' . get_permalink($post->ID) . '"><h2>' . get_the_title($post->ID) . '</h2>';
    $excerpt = get_post_excerpt($post->ID); <<<<<<<<<<<<----- HERE
    if (strlen($excerpt) > 135) {
    $excerpt = substr($excerpt, 0, 135) . '...';
            }
echo '<p>'. $excerpt .'</p>';
    echo '</a></article></li>';
}

echo '</ul>';
}

Thanks

Related posts

Leave a Reply

1 comment

  1. I might be wrong but isn´t the $post variable in the foreach an object?
    If so you could do $post->post_excerpt;

    EDIT:
    After looking more into it I´ve found that this won´t work.
    But you can easily adjust your script to work the way you want it to.

    foreach($posts as $post){
        setup_postdata($post);
        $excerpt = get_the_excerpt(); 
    
        if (strlen($excerpt) > 135) {
           $excerpt = substr($excerpt, 0, 135) . '...';
        }
    
        printf(
            '<li><article><a href="%s"><h2>%s</h2><p>%s</p></a></article></li>', 
            get_permalink(), 
            get_the_title(),
            $excerpt
        );
    }
    

    I´ve not tested it, but it should work.

    In the example on the get_post page you can see how the setup_postdata is used.

    Also note, that it says on the get_the_excerpt page that the parameter of the function is deprecated.