Created
September 3, 2014 17:55
-
-
Save joemcgill/da79e4f9c96480123ef2 to your computer and use it in GitHub Desktop.
Wordpress Widow Busting Function
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 | |
/** | |
* Avoid widows in text by replacing the final space in each paragraph with a | |
* | |
* Inspired by David Walsh (http://davidwalsh.name/word-wrap-mootools-php) | |
* | |
* @param string $content Content passed into the filter | |
* @return string the filtered content | |
*/ | |
function wustl_widow_buster ($content) { | |
$return = $content; | |
$min_words = 3; // don't break small graphs | |
$graphs_in = explode("</p>", $content); // break the graphs | |
$graphs_out = array(); // set up the collector array | |
foreach( $graphs_in as $graph ) { | |
$word = explode(' ',$graph); // break each word | |
if( count($word) >= $min_words ) { | |
$word[count($word) - 2] .= ' '.$word[count($word) - 1]; | |
array_pop($word); | |
} | |
$graphs_out[] = implode(' ',$word); // rebuild graphs from words | |
} | |
$return = implode("</p>", $graphs_out); // rebuild text from | |
return $return; | |
} | |
add_filter( 'the_content', 'wustl_widow_buster'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment