Skip to content

Instantly share code, notes, and snippets.

@bobbydank
Last active July 8, 2024 16:39
Show Gist options
  • Save bobbydank/0d1bcb07607c068e761b11b7e8195c2f to your computer and use it in GitHub Desktop.
Save bobbydank/0d1bcb07607c068e761b11b7e8195c2f to your computer and use it in GitHub Desktop.
<?php
/**
* Filter the except length to any specified length of words.
*
* @param string $content the content
* @param int $length Excerpt length.
* @return int (Maybe) modified excerpt length.
*/
function catchy_labs_custom_excerpt($content, $limit) {
// Remove HTML tags
$content = strip_tags($content);
// Remove URLs
$content = preg_replace('/\bhttps?:\/\/\S+/i', '', $content);
// Split the content into words and limit the number of words
$excerpt = explode(' ', $content, $limit);
if (count($excerpt) >= $limit) {
array_pop($excerpt);
$excerpt = implode(" ", $excerpt) . ' [...]';
} else {
$excerpt = implode(" ", $excerpt);
}
// Remove any remaining shortcode-like content
$excerpt = preg_replace('`\[[^\]]*\]`', '', $excerpt);
return $excerpt;
}
?>
<div class="the-excerpt">
<p><?php echo catchy_labs_custom_excerpt( get_the_content(), 45 ); ?></p>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment