php – 将WP摘录限制为第二句

我正在使用此功能将我的WP摘录限制为一个句子,而不是仅仅在一些单词之后将其删除.

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);
}

像魅力一样工作,但我想将其限制为两句话.任何人都知道如何做到这一点?

最佳答案 你的代码对我来说不适用于1个句子,但是嘿,这是凌晨2点,也许我错过了一些东西.我是从头开始写的:

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);
}
点赞