Trim and format WordPress post content as an excerpt
By default, when you access the WordPress $post object, the $post->post_excerpt item is always empty UNLESS you manually handcrafted an excerpt for that particular post. This portion of code is a workaround if you only need the excerpt. It trims the $post->post_content, strips out formating and tacks a Read More link on the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php $content = strip_tags(strip_shortcodes($item->post_content)); $content = str_replace(array("\r\n","\n\n",' '),' ',$content); $words = explode(' ',$content); if (count($words) > 40) { $excerpt = implode(' ',array_slice($words,0,40)) .'<a href="'.get_permalink($post->ID).'">[Read More]</a>'; } else { $excerpt = $content; } echo ' <div>'.$excerpt.'</div> '; ?> |
<?php
$content = strip_tags(strip_shortcodes($item->post_content));
$content = str_replace(array("\r\n","\n\n",' '),' ',$content);
$words = explode(' ',$content);
if (count($words) > 40) {
$excerpt = implode(' ',array_slice($words,0,40))
.'<a href="'.get_permalink($post->ID).'">[Read More]</a>';
} else {
$excerpt = $content;
}
echo '
<div>'.$excerpt.'</div>
';
?>
No Responses