Search code examples
wordpresspreg-replacetrim

Customizing what WordPress get_the_content(); returns


I want to limit get_the_content(); to a specific number of characters, say 100. If the last character falls within a word, i.e. it doesn't have a space after it, I want to trim back to the previous character that has a space after it, and store this in get_the_content(). How do I do this?


Solution

  • You want to use a filter.

    Something like:

    function my_the_content_filter($content) {
      // wordwrap wraps a line after x number of characters but doesn't break words.  then use regex to delete everything after the first linebreak.
      echo preg_replace('/\\\n(.*)/', '', wordwrap ( $string, 100, '\n'));
      return $content;
    }
    
    add_filter( 'the_content', 'my_the_content_filter' );