Skip to content

Instantly share code, notes, and snippets.

@tylerforret
Last active April 15, 2016 16:57
Show Gist options
  • Save tylerforret/82a8c1b2fcd994460dfe to your computer and use it in GitHub Desktop.
Save tylerforret/82a8c1b2fcd994460dfe to your computer and use it in GitHub Desktop.
Wordpress Custom Excerpt Lengths w/ Links
<?php
// Custom excerpt lengths
function get_excerpt($count){
$permalink = get_permalink($post->ID);
$words = array();
$excerpt = get_the_content();
$excerpt = strip_tags($excerpt, '<a>'); //allow links within excerpt
$excerpt = strip_shortcodes( $excerpt );
$excerpt = substr($excerpt, 0, $count);
$excerpt = $excerpt;
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
return $excerpt;
}
// Remove ...
function trim_excerpt($text) {
return rtrim($text,'[...]');
}
?>
@tylerforret
Copy link
Author

Function to add custom excerpt lengths to a theme and allow links in the excerpt (by default links are stripped from excerpts in WordPress). This function also removes the "..." at the end of excerpts. Exclude lines 21-24 if you still want them.

Just add the above code to the theme's existing functions.php file.

Front end code needs to be in the loop.

Front End Usage '###' is character length:

<?php echo get_excerpt('###'); ?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment