Search code examples
phphtmlwordpressposts

Wordpress Limit Word of a post disables formatting


I've put a limit on my post length by creating a custom wordpress plugin. But this creates a new issue where the layout of my blog posts is destroyed.

Lay-Out Without The Plugin Activated:

https://i.sstatic.net/LjUAr.jpg

Lay-Out With The Plugin Activated:

https://i.sstatic.net/nJJHa.jpg

function limit_words_on_posts($content)
{
// Get the post content
$post_type = get_post_type();
if ($post_type == 'post'){
$post = get_post();
$url = 'https://www.vierenzestig.nl/';
$postslug = $post->post_name;

// Limit the post content
$text = $content;
$words = 300; 
$link = $url . $postslug;
$more = '...<br/><br/><strong>Wilt u dit artikel verder lezen? <a style="color: red; text- 
decoration: underline;" href="'.$link.'">Ga dan naar VierenZestig.NL!</a></strong>';


$excerpt = wp_trim_words( $text, $words, $more );

return $excerpt;
} else {
return $content;
}

}

As you can see the line breaks etc are removed while using the plugin. Is there something I'm missing?


Solution

  • The wp_trim_words strip all tags from the content it has.

    You can use this code:

    $excerpt = force_balance_tags(html_entity_decode(wp_trim_words(htmlentities($text), $words, $more)));