I am using get_posts to retrieve posts information from database. It returns "Post title", "thumbnail", "post category", and "post excerpt". Everything is working fine but the problem is I am unable to show post excerpt.
Here is my code:
function widget ($args,$instance) {
extract($args);
$title = $instance['title'];
$catid = $instance['catid'];
$numberposts = $instance['numberposts'];
$date = $instance['date'];
$rss = $instance['rss'];
// retrieve posts information from database
global $wpdb;
$posts = get_posts('post_type=post&numberposts='.$numberposts.'&category='.$catid);
$out = '<ul>';
if ($posts) {
foreach($posts as $post) {
setup_postdata($post);
$out .= '<li>'.get_the_post_thumbnail($post->ID,'medium').'</li>';
$out .= '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
$out .= '<li>'.$post->post_excerpt.'</li>';
if ($date) $out .= '<li>'.date('d/m/Y', strtotime($post->post_date_gmt)).'</li>';
}
}
if ($rss) $out .= '<li><a href="'.get_category_link($catid).'feed/" class="rss">Category RSS</a></li>';
$out .= '</ul>';
//print the widget for the sidebar
echo $before_widget;
echo $before_title.$title.$after_title;
echo $out;
echo $after_widget;
}
}
$post->post_excerpt
does not get work the way you think it does. Most people think this is the same as the template tag the_excerpt()
, and it is not
the_excerpt()
is generated by truncating get_the_content()
. $post->post_excerpt
is not generated at all as this is user defined. This excerpt is the excerpt text manually added by the user in the post edit screen in the excerpt meta box. (This meta box is hidden by default, but can be enabled in the "Screen Options" tab on the top part of the screen). If the user did not specify a manual excerpt, $post->post_excerpt
will return nothing, that is why you see this behavior
You have already set up your postdata, so you can just simply use the template tags directly, so in place of $post->post_excerpt
, you can use the_excerpt()
EDIT
Thanks to the comment below, I did not take into account that the excerpt should not be echo'd straight away. In this case, you would make use of get_the_excerpt()
which does not echo the text, but simply retrieves it.