Reputation: 395
I am new to wordpress and php. I am trying to get the excerpt of a post retrieved using foreach in wordpress. I am trying to display all the posts on a page but I dont want to display the whole content I want only excerpt.
I am able to displat the title but unable to get the excerpt.
I have tried: $excerpt = get_post_excerpt($post)
,$excerpt = get_the_excerpt($post);
, $excerpt = $post->the_excerpt()
please also tell me if iam missing some basics.
here is my full code
<?php
function some_code() {
// query
$query = 'orderby=date&order=asc&posts_per_page=-1';
$wpq = new WP_Query($query);
$posts = $wpq->get_posts();
foreach($posts as $post)
{
$link = get_permalink($post);
echo "<a href='$link'><h3>{$post->post_title}</h3></a>";
$excerpt = get_the_excerpt($post);
echo "$excerpt";
}
}
?>
Upvotes: 1
Views: 433
Reputation: 11462
An easy solution compatible with your code would be to use setup_postdata($post);
inside your foreach
loop, which makes all the post related data available:
$query = 'orderby=date&order=asc&posts_per_page=-1';
$wpq = new WP_Query($query);
$posts = $wpq->get_posts();
foreach($posts as $post)
{
setup_postdata($post);
$excerpt = get_the_excerpt($post);
echo $excerpt;
}
More about setup_postdata()
can be found here.
Try this also if that doesn't work, I think using a traditional loop instead of foreach
is a better approach:
$query = array('orderby' => 'date', 'order' => 'asc', 'posts_per_page' => '-1');
$wpq = new WP_Query($query);
if($wpq->have_posts()){
while($wpq->have_posts()){
$wpq->the_post();
the_excerpt();
}
}
Or you can use a function called wp_trim_words
:
echo wp_trim_words( $post->post_content );
Upvotes: 1