Created
September 5, 2012 12:36
-
-
Save AramZS/3635943 to your computer and use it in GitHub Desktop.
a 'killer' excerpt that allows you to include formatting tags and control the excerpt based on wordcount.
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
| //Set the function up to receive any custom excerpt set by the user. | |
| function a_killer_excerpt( $text ) { | |
| //We'll be using the post object, so we need to call the global object down to play with later. | |
| global $post; | |
| //This if loop makes it so it will only display this modified excerpt if the user hasn't manually set one. | |
| if ( '' == $text ) { | |
| //Get the full content of the post. | |
| $text = get_the_content(''); | |
| //Apply all the_content's standard filters. | |
| $text = apply_filters('the_content', $text); | |
| $text = str_replace('\]\]\>', ']]>', $text); | |
| $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text); | |
| //Tags you want to include in the excerpt. | |
| $text = strip_tags($text, '<p> <strong> <bold> <i> <em> <emphasis> <del> <h1> <h2> <h3> <h4> <h5>'); | |
| $excerpt_length = 100; //Word count | |
| //The following turns the received text into an array, with each space-separated word as an item. | |
| //This lets PHP count the number of words and remove all but the first $excerpt_length count of words. | |
| $words = explode(' ', $text, $excerpt_length + 1); | |
| if (count($words)> $excerpt_length) { | |
| //This pops the last word off the array... | |
| array_pop($words); | |
| //...and replaces it with an ellipsis. | |
| array_push($words, '...'); | |
| //Then we merge it back into a string. | |
| $text = implode(' ', $words); | |
| } | |
| } | |
| //The last action is to return the now modified string back to the theme to display. | |
| return $text; | |
| } | |
| //Tell WordPress that we don't want to use its boring excerpt code. | |
| remove_filter('get_the_excerpt', 'wp_trim_excerpt'); | |
| //Tell WordPress to use this excerpt code instead. | |
| add_filter('get_the_excerpt', 'a_killer_excerpt'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment