Last active
November 16, 2020 16:14
-
-
Save FernE97/4710481 to your computer and use it in GitHub Desktop.
PHP: WordPress modified wp_trim_words to include tags
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
<?php | |
// Custom Excerpt | |
function custom_trim_words( $text, $num_words = 55, $more = null ) { | |
if ( null === $more ) | |
$more = __( '…' ); | |
$original_text = $text; | |
$text = strip_shortcodes( $text ); | |
// Add tags that you don't want stripped | |
$text = strip_tags( $text, '<strong>, <b>, <em>, <i>' ); | |
if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && 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 ); | |
} | |
return apply_filters( 'custom_trim_words', $text, $num_words, $more, $original_text ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If this splits on an element, say middle of an
<a>
tag this absolutely destroys the layout. For example, if using this inside of a loop and you trim the excerpt mid<a>
tag, all of the following elements will be nested inside this one.