1

I have a get_the_content() Wordpress code as you can see below. I want to force the code to do the following:

  • Don't display empty tags as nbsp; (works now)
  • Display only a limited amount of words (don't know how)

I added this code to my home.php:

<?php 
$content = get_the_content('Read more');
$content = str_replace('&nbsp;'," ", get_the_content());
$content = preg_replace( '/\s+/', ' ', $content );
echo $content; 
?>

It works, but i want to display only a limited amount of words now. All the solutions as $char_limit and wp_trim_words() are not the solutions i am looking for, because they are mess up the blog posts.

What can i do?

2 Answers2

0

Use this handy utility function for restricting word count with respect to words described in here Get first 100 characters from string, respecting full words

function truncate($text, $length) {
   $length = abs((int)$length);
   if(strlen($text) > $length) {
      $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
   }
   return(str_replace('&nbsp;'," ", $text));
}

Pass the values like

$content = get_the_content('Read more');
print_r(truncate($content, 180));
Saad Suri
  • 1,352
  • 1
  • 14
  • 26
0
function limitText($text, $limit)
{
    $count = strlen($text);
    if ($count >= $limit) {
        $text = substr($text, 0, strrpos(substr($text, 0, $limit), ' ')) . '...';

        return $text;
    } else {
        return $text;
    }
}

And the echo

 <?= limitText(get_the_content(), 30); ?>
Gustavo Chagas
  • 344
  • 1
  • 13