Home / Admin / WordPress Typography Enhancement: Preventing Widows in Conten
Duplicate Snippet

Embed Snippet on Your Site

WordPress Typography Enhancement: Preventing Widows in Conten

This code is a WordPress filter designed to prevent "widows" in typography within the content displayed on a WordPress site. In typography, a widow is a short line or a single word that appears alone at the end of a paragraph, separated from the rest of the text. The goal of this code is to add non-breaking spaces ( ) between certain words in specific HTML tags to avoid widows.

The function is named kl_avoid_content_widows and takes the content of a post or page as its input. It uses a regular expression to identify instances where three words are separated by spaces within certain HTML tags (paragraphs and heading tags from h1 to h6), and it replaces the spaces with non-breaking spaces.

Here's a breakdown of the regular expression and replacement:

The regular expression ($pattern) captures three groups of words within specific HTML tags, separated by spaces.
The replacement ($replacement) inserts non-breaking spaces between the captured words.
The preg_replace function is then used to perform the replacement in the content.
Finally, the filter is applied to the WordPress 'the_content' hook, meaning it affects the content displayed on posts and pages.

In summary, this code aims to enhance the typographic appearance of the content by preventing widows within specified HTML tags, ensuring that certain words stay together at the end of paragraphs or headings.

<10
Code Preview
php
<?php
/**
 * Avoid Typography Widows
 */
function kl_avoid_content_widows( $content ) {
    $pattern = '@(?:\s)([[:punct:][:word:]]+)(?:\s)(?!/>)([[:punct:][:word:]]+)(?:\s)([[:punct:][:word:]]+)</(p|h1|h2|h3|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' );

Comments

Add a Comment