Limit WP excerpt to second sentence

I’m using this function to limit my WP excerpt to a sentence instead of just cutting it off after a number of words.

add_filter('get_the_excerpt', 'end_with_sentence');

function end_with_sentence($excerpt) {
  $allowed_end = array('.', '!', '?', '...');
  $exc = explode( ' ', $excerpt );
  $found = false;
  $last = '';
  while ( ! $found && ! empty($exc) ) { 
    $last = array_pop($exc);
    $end = strrev( $last );
    $found = in_array( $end{0}, $allowed_end );
  }
  return (! empty($exc)) ? $excerpt : rtrim(implode(' ', $exc) . ' ' .$last);
}

Works like a charm, but I would like to limit this to two sentences. Anyone have an idea how to do this?

Related posts

2 comments

  1. Your code didn’t work for me for 1 sentence, but hey it’s 2am here maybe I missed something. I wrote this from scratch:

    add_filter('get_the_excerpt', 'end_with_sentence');
    
    function end_with_sentence( $excerpt ) {
      $allowed_ends = array('.', '!', '?', '...');
      $number_sentences = 2;
      $excerpt_chunk = $excerpt;
    
      for($i = 0; $i < $number_sentences; $i++){
          $lowest_sentence_end[$i] = 100000000000000000;
          foreach( $allowed_ends as $allowed_end)
          {
            $sentence_end = strpos( $excerpt_chunk, $allowed_end);
            if($sentence_end !== false && $sentence_end < $lowest_sentence_end[$i]){
                $lowest_sentence_end[$i] = $sentence_end + strlen( $allowed_end );
            }
            $sentence_end = false;
          }
    
          $sentences[$i] = substr( $excerpt_chunk, 0, $lowest_sentence_end[$i]);
          $excerpt_chunk = substr( $excerpt_chunk, $lowest_sentence_end[$i]);
      }
    
      return implode('', $sentences);
    }
    
  2. I see complexities in your sample code that make it (maybe) harder than it needs to be.

    Regular expressions are awesome. If you want to modify this one, I’d recommend using this tool: https://regex101.com/

    Here we’re going to use preg_split()

    function end_with_sentence( $excerpt, $number = 2 ) {
        $sentences = preg_split( "/(.|!|?|...)/", $excerpt, NULL, PREG_SPLIT_DELIM_CAPTURE);
    
        var_dump($sentences);
    
        if (count($sentences) < $number) {
             return $excerpt;
        }
    
        return implode('', array_slice($sentences, 0, ($number * 2)));
    }
    

    Usage

    $excerpt = 'Sentence. Sentence!  Sentence? Sentence';
    
    echo end_with_sentence($excerpt); // "Sentence. Sentence!"
    echo end_with_sentence($excerpt, 1); // "Sentence."
    echo end_with_sentence($excerpt, 3); // "Sentence. Sentence!  Sentence?"
    echo end_with_sentence($excerpt, 4); // "Sentence. Sentence!  Sentence? Sentence"
    echo end_with_sentence($excerpt, 10); // "Sentence. Sentence!  Sentence? Sentence"
    

Comments are closed.