wp_trim_words() does not trim the_content() in WordPress

The problem lies in this line:

<?php echo wp_trim_words( the_content(), 55, $moreLink); ?>

You call the_content function in there. This function prints all the content and doesn’t return anything. It means that you print the content, and then pass an empty string to the wp_trim_words.

It should be:

<?php echo wp_trim_words( get_the_content(), 55, $moreLink); ?>

Be careful because, as described in codex, get_the_content() does not pass the content through the ‘the_content’ filter. This means it won’t execute shortcodes. If you want to get exactly what the_content() prints, you have to use

<?php
$my_content = apply_filters( 'the_content', get_the_content() );
echo wp_trim_words( $my_content, 55, $moreLink);
?>

I suggest to also use wp_strip_all_tags(), otherwise you may have problems with open tags that have been trimmed.

Full example:

<?php
$my_content = apply_filters( 'the_content', get_the_content() );
$my_content = wp_strip_all_tags($my_content);
echo wp_trim_words( $my_content, 55, $moreLink);
?>

Leave a Comment