How to Fix Typographic Widows / Orphans in WordPress

Have you ever wanted to know how to fix a word that wraps to its own line on a WordPress page or article? There is a way to do this using just a little bit of code inserted into your theme’s function.php file.

I found this out through https://www.kevinleary.net/blog/fix-hanging-words-wordpress/#how-to-fix-typographic-widows-in-wordpress.

However, the code I inserted into my function.php was changed to look like this::

/**
 * Avoid Typography Widows
 */
function kl_avoid_content_widows( $content ) {
    $pattern = '@(?:\s)([[:punct:][:word:]]+)(?:\s)(?!/>)([[:punct:][:word:]]+)(?:\s)([[:punct:][:word:]]+)</(p|h1|h2|h4|h5|h6)>@m';
    $replacement = '&nbsp;$1&nbsp;$2&nbsp;$3</$4>';
    $content = preg_replace( $pattern, $replacement, $content, -1 );

    return $content;
}
add_filter( 'the_content', 'kl_avoid_content_widows' );

I omitted the h3 since it was causing a style conflict.

There was another solution at https://www.binarymoon.co.uk/2017/04/fixing-typographic-widows-wordpress/ , but it didn’t work. I will have to explore this topic further to figure out why.



Leave a Reply

Your email address will not be published. Required fields are marked *