yanknudtskov
11/29/2016 - 6:40 PM

Perfect Excerpts for WordPress

Perfect Excerpts for WordPress

// use this inside loop
// 220 is the character limit, you can change it to whatever value you need

<?php echo perfect_excerpt(220); ?>
// if you're tired of excerpts cutting in half, here it is, the perfect solution
// that shortens your excerpt to full sentences in your characters limit.
<?php
function perfect_excerpt( $length ) {
  $excerpt = get_the_excerpt();
  $short_excerpt = substr($excerpt, 0, $length);
  
  // look for the last period
  $finishline = strrpos( $short_excerpt, '.');
	
  // period not found, check for question mark
  if (empty($finishline)) {
    $finishline = strrpos( $short_excerpt, '?');
  }
  
  // question mark also not found, search for exclamation mark
  if (empty($finishline)) {
  $finishline = strrpos( $short_excerpt, '!');
  }
  
  // now we need check if there are really long first sentences
  // that don't have periods, exclamation or question mark
  // in our characters limit
  // and if so, we'll just trim them and add ...
  
  if (empty($finishline)) {
    $final = $short_excerpt .'...';
  } else {
    $final = substr($short_excerpt, 0, $finishline+1);
	}

  return wpautop($final);
}
?>