I am using <?php echo wp_trim_words(get_the_content(), 100); ?>
in my template file to control amount of words to be displayed on a page and also have a link below it for taking user to the next page to read entire content but this function removes all the formatting of content on preview page.
I can’t use wordpress default excerpt function here as it is being used elsewhere and i need this to be of different length than that. Is there a way to retain formatting while using this ?
Thanks
I found a solution to this may be it can help others as well.
function content_excerpt($excerpt_length = 5, $id = false, $echo = true) {
$text = '';
if($id) {
$the_post = & get_post( $my_id = $id );
$text = ($the_post->post_excerpt) ? $the_post->post_excerpt : $the_post->post_content;
} else {
global $post;
$text = ($post->post_excerpt) ? $post->post_excerpt : get_the_content('');
}
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$words = preg_split("/[nrt ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
if($echo)
echo apply_filters('the_content', $text);
else
return $text;
}
function get_content_excerpt($excerpt_length = 5, $id = false, $echo = false) {
return content_excerpt($excerpt_length, $id, $echo);
}
// Call function in template file via
<?php content_excerpt(50); // 50 is amount to words ?>
To anyone else facing similar issues, I took the default
wp_trim_words()
function directly out of core, and altered it to not strip tags:Try:
echo apply_filters( 'the_content', wp_trim_words( get_the_content(), 100 ) );