Last active
November 30, 2015 04:18
-
-
Save mandiwise/f7928ba3e3e8bcfdb28e to your computer and use it in GitHub Desktop.
Custom WP excerpts (with allowed HTML tags and custom read more link)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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( ']]>', ']]>', $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 →</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