Skip to content

Instantly share code, notes, and snippets.

@timwhitlock
Created February 2, 2012 16:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timwhitlock/1724489 to your computer and use it in GitHub Desktop.
Save timwhitlock/1724489 to your computer and use it in GitHub Desktop.
Simple wordpress plug to avoid typographical widows
<?php
/*
Plugin Name: No Widows
Plugin URI: http://timwhitlock.info/
Description: Prevents typographical widows in titles and post body content
Author: Tim Whitlock
Version: 1.0
Author URI: http://timwhitlock.info/
*/
/**
* Filter function, prevents all end of lines breaking with a widow
* @param string original html-encoded text
* @return string new widowless html
*/
function no_widows_filter_html( $html ){
return preg_replace_callback( '/(\s+)(\S+)$/m', 'no_widows_filter_html_callback', $html);
}
/**
* Replacement callback function
* @internal
*/
function no_widows_filter_html_callback( array $match ){
list(,,$word) = $match;
// word may also contain breaking characters
$hyphens = array (
'-',
'&ndash;', '&#8211;', '&#x2013;', "\x2013",
'&mdash;', '&#8212;', '&#x2014;', "\x2014",
);
// replace any dash with non-breaking hyphen
$word = str_ireplace( $hyphens, '&#8209;', $word );
// return widow with single non-breaking space in place of whitespace
return '&nbsp;'.$word;
}
// apply filter to title and content as desired
add_filter('the_title','no_widows_filter_html');
add_filter('the_content','no_widows_filter_html');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment