Reputation: 1637
How can I get the first few words of a post that does not have excerpt?
$args = array(
'posts_per_page' => 5,
'offset' => 0,
'category' => '',
'category_name' => 'Energy',
'orderby' => 'date',
'order' => 'DESC',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'post',
'post_mime_type' => '',
'post_parent' => '',
'author' => '',
'author_name' => '',
'post_status' => 'publish',
'suppress_filters' => true
);
$posts_array = get_posts( $args );
foreach($posts_array as $postCategory)
{
echo get_the_title( $postCategory->ID );
echo get_permalink( $postCategory->ID );
echo get_the_excerpt( $postCategory->ID ); // THIS WITH OU WITHOUT EXCERPT DOES NOT WORK
}
The code is printing the title and the permalink but it does not print the first few words of the post.
I would like to understand how to print the first few words of the post, whether or not it has the excerpt delimiter.
Thanks
Upvotes: 1
Views: 903
Reputation: 59
$trimtitle = get_the_content($post->ID);
$shorttitle = wp_trim_words( $trimtitle, $num_words = 15, $more = '… ' );?>
<?php echo $shorttitle; ?>
Upvotes: 3
Reputation: 1750
To do this, you'll need to add the following function:
function truncate_string ($string, $maxlength) {
// Set the replacement for the "string break" in the wordwrap function
$cutmarker = "**cut_here**";
// Checking if the given string is longer than $maxlength
if (strlen($string) > $maxlength) {
// Using wordwrap() to set the cutmarker
// NOTE: wordwrap (PHP 4 >= 4.0.2, PHP 5)
$string = wordwrap($string, $maxlength, $cutmarker);
// Exploding the string at the cutmarker, set by wordwrap()
$string = explode($cutmarker, $string);
}
// returning $string
return $string;
}
Then add the following inside your foreach loop:
$content_post = get_post( $postCategory->ID );
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo truncate_string( $content, 75 );
(change 75 to whatever length you'd like)
Upvotes: 0