2

I have this simple shortcode to display the last posts with it's title and except:

add_shortcode('latest3', function(){
    $recent_posts = wp_get_recent_posts(
            array(
                'numberposts'   => 3,
                'orderby'       => 'post_date',
                'order'         => 'DESC',
                'post_type'     => 'post',
                'post_status'   => 'publish'
            ), ARRAY_A);

    $output = '<h2>Latest posts</h2>';
    foreach ( $recent_posts as $recent ) {
        $output .= '<h3>'.$recent["post_title"].'</h3>';
        $output .= $recent["post_excerpt"];
    }
    return $output;
});

But for some reason the excerpt output is empty. print_r($recents) shows that there is indeed an array key called post_excerpt but is shown always empty.

2 Answers 2

3

The post_excerpt value is empty because you have no explicit excerpts for your posts. While the_excerpt() does generate an excerpt from the posts content if the post excerpt is empty, the function wp_get_recent_posts(), which is basically a wrapper for get_posts(), doesn't.

2
  • makes sense. Thought that in this case the excerpt would return the excerpt of the post content itself. Thanks Sep 11, 2014 at 13:16
  • My pleasure. I'd say thats what will commonly happen, if you are not that familiar with WP. You might want to take a look at this Q&A's or you do what Tomás Cot suggested. @Th3Alchemist Sep 11, 2014 at 13:20
4

This code could work, I'm using the setup_postdata to create a post object similar to what the function the_post() does, so now you can use the functions you have in a Loop.

$recent_posts = wp_get_recent_posts(
            array(
                'numberposts'   => 3,
                'orderby'       => 'post_date',
                'order'         => 'DESC',
                'post_type'     => 'post',
                'post_status'   => 'publish'
            ), OBJECT);

    $output = '<h2>Latest posts</h2>';
    foreach ( $recent_posts as $recent ) {
        setup_postdata($recent);
        $output .= '<h3>'.get_the_title().'</h3>';
        $output .= get_the_excerpt();
    }
    wp_reset_postdata();
    return $output;
5
  • Better be save than sorry and add wp_reset_postdata() Sep 11, 2014 at 13:27
  • I don't think it's neccesary in this context, but, yes, it can be added just to be safe.
    – Tomás Cot
    Sep 11, 2014 at 14:00
  • Like i said: »better be save than sorry« :) Sep 11, 2014 at 14:01
  • It is not neccessary to setup_postdata($recent) You can just use $recent in get_the_tilte($recent) and get_the_except($recent)
    – Tofandel
    Aug 6, 2018 at 11:43
  • what's the diff between wp_reset_postdata(); and wp_reset_query(); in this case? Mar 23, 2019 at 3:44

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.