Skip to content

Instantly share code, notes, and snippets.

@joemcgill
Created September 3, 2014 17:55
Show Gist options
  • Save joemcgill/da79e4f9c96480123ef2 to your computer and use it in GitHub Desktop.
Save joemcgill/da79e4f9c96480123ef2 to your computer and use it in GitHub Desktop.
Wordpress Widow Busting Function
<?php
/**
* Avoid widows in text by replacing the final space in each paragraph with a &nbsp;
*
* 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] .= '&nbsp;'.$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