Created
June 7, 2018 01:03
-
-
Save swinggraphics/4ca551447bec03da281424c4ff85dcfd to your computer and use it in GitHub Desktop.
WordPress strips out tags in `wp_trim_words()`, which is called by `get_the_excerpt()`; so we have to filter 'wp_trim_words', basically copying that function with one change: replace `wp_strip_all_tags()` with `strip_tags()`. We don't want other functions that run `wp_trim_words` to be modified, so we add our filter while `get_the_excerpt()` is …
This file contains hidden or 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
// Allow links in excerpts | |
function sg_trim_words( $text, $num_words, $more, $original_text ) { | |
$text = strip_tags( $original_text, '<a>' ); | |
// @See wp_trim_words in wp-includes/formatting.php | |
if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) { | |
$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' ); | |
preg_match_all( '/./u', $text, $words_array ); | |
$words_array = array_slice( $words_array[0], 0, $num_words + 1 ); | |
$sep = ''; | |
} else { | |
$words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY ); | |
$sep = ' '; | |
} | |
if ( count( $words_array ) > $num_words ) { | |
array_pop( $words_array ); | |
$text = implode( $sep, $words_array ); | |
$text = $text . $more; | |
} else { | |
$text = implode( $sep, $words_array ); | |
} | |
// Remove self so we don't affect other functions that use wp_trim_words | |
remove_filter( 'wp_trim_words', 'sg_trim_words' ); | |
return $text; | |
} | |
// Be sneaky: add our wp_trim_words filter during excerpt_more filter, which is called immediately prior | |
function sg_add_trim_words_filter( $excerpt_length ) { | |
add_filter( 'wp_trim_words', 'sg_trim_words', 10, 4 ); | |
return $excerpt_length; | |
} | |
add_filter( 'excerpt_more', 'sg_add_trim_words_filter', 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment