Skip to content

Instantly share code, notes, and snippets.

@AustinGil
Last active November 15, 2017 14:56
Show Gist options
  • Save AustinGil/4ef596130b0474972ee58e08429f6495 to your computer and use it in GitHub Desktop.
Save AustinGil/4ef596130b0474972ee58e08429f6495 to your computer and use it in GitHub Desktop.
Function for better truncating text in WordPress. Great for custom excerpts.
/**
* Takes a string and returns a truncated version. Also strips out shortcodes
*
* @param string $text String to truncate
* @param integer $length Character count limit for truncation
* @param string $append Appended to the end of the string if character count exceeds limit
* @return string Truncated string
*/
function truncate_text( $text='', $length = 50, $append = '...') {
$new_text = preg_replace(" ([.*?])",'',$text);
$new_text = strip_shortcodes($new_text);
$new_text = strip_tags($new_text);
$new_text = substr($new_text, 0, $length);
if ( strlen($new_text) == $length ) {
$new_text = substr($new_text, 0, strripos($new_text, " "));
$new_text = $new_text . $append;
}
return $new_text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment