Skip to content

Instantly share code, notes, and snippets.

@mandiwise
Last active November 30, 2015 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mandiwise/f7928ba3e3e8bcfdb28e to your computer and use it in GitHub Desktop.
Save mandiwise/f7928ba3e3e8bcfdb28e to your computer and use it in GitHub Desktop.
Custom WP excerpts (with allowed HTML tags and custom read more link)
<?php
/**
* Customize excerpt length and style.
*
* @param string The raw post content.
* @return string
*/
function red_wp_trim_excerpt( $text ) {
$raw_excerpt = $text;
if ( '' == $text ) {
// retrieve the post content
$text = get_the_content('');
// delete all shortcode tags from the content
$text = strip_shortcodes( $text );
$text = apply_filters( 'the_content', $text );
$text = str_replace( ']]>', ']]&gt;', $text );
// indicate allowable tags
$allowed_tags = '<p>,<a>,<em>,<strong>,<blockquote>,<cite>';
$text = strip_tags( $text, $allowed_tags );
// change to desired word count
$excerpt_word_count = 50;
$excerpt_length = apply_filters( 'excerpt_length', $excerpt_word_count );
// create a custom "more" link
$excerpt_end = '<span>[...]</span><p><a href="' . get_permalink() . '" class="read-more">Read more &rarr;</a></p>'; // modify excerpt ending
$excerpt_more = apply_filters( 'excerpt_more', ' ' . $excerpt_end );
// add the elipsis and link to the end if the word count is longer than the excerpt
$words = preg_split( "/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY );
if ( count( $words ) > $excerpt_length ) {
array_pop( $words );
$text = implode( ' ', $words );
$text = $text . $excerpt_more;
} else {
$text = implode( ' ', $words );
}
}
return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
}
remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
add_filter( 'get_the_excerpt', 'red_wp_trim_excerpt' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment