Created
November 27, 2016 21:51
-
-
Save hellofromtonya/e2b4cd101cb308044c1ecc8339f7cb6a to your computer and use it in GitHub Desktop.
Content Limiter - truncate to number of words
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 | |
| /** | |
| * Limit the content by the number of words. | |
| * | |
| * @package - | |
| * @since 1.0.0 | |
| * @author hellofromTonya | |
| * @link https://UpTechLabs.io | |
| * @license GPL-2+ | |
| */ | |
| add_filter('the_content', 'truncate_the_content', 99); | |
| /** | |
| * Truncate the content to a set number of words. | |
| * | |
| * @since 1.0.0 | |
| * | |
| * @param string $text | |
| * | |
| * @return string | |
| */ | |
| function truncate_the_content( $text ) { | |
| if ( is_singular() ) { | |
| return $text; | |
| } | |
| $text = strip_shortcodes( $text ); | |
| return truncate_text( $text ); | |
| } | |
| /** | |
| * Truncate the incoming string of text to a set number of words. | |
| * It preserves the HTML markup. | |
| * | |
| * @since 1.0.0 | |
| * | |
| * NOTE: This function is adapted from WordPress Core's `wp_trim_words()` | |
| * function. It does the same functionality, except it does not strip out | |
| * the HTML tag elements. | |
| * | |
| * @param string $text | |
| * @param int $words_limit | |
| * @param string $more_text | |
| * | |
| * @return string | |
| */ | |
| function truncate_text( $text, $words_limit = 55, $more_text = '…' ) { | |
| $separator = ' '; | |
| /* | |
| * translators: If your word count is based on single characters (e.g. East Asian characters), | |
| * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'. | |
| * Do not translate into your own language. | |
| */ | |
| 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, $words_limit + 1 ); | |
| $separator = ''; | |
| } else { | |
| $words_array = preg_split( "/[\n\r\t ]+/", $text, $words_limit + 1, PREG_SPLIT_NO_EMPTY ); | |
| } | |
| if ( ! count( $words_array ) > $words_limit ) { | |
| return implode( $separator, $words_array ); | |
| } | |
| array_pop( $words_array ); | |
| $text = implode( $separator, $words_array ); | |
| return $text . $more_text; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment