How to automatically insert non-breaking space in WordPress

In french, we add a space before signs: !?:

In order to avoid line breaks before these signs, here’s a function that will automatically add non-breaking spaces before:

<?php
/*
* Add unbreakable spaces before !?:
*/
add_filter('the_title', 'wpster_addUnbreakableSpace');
add_filter('the_content', 'wpster_addUnbreakableSpace');
add_filter("acf_the_content", "wpster_addUnbreakableSpace");
function wpster_addUnbreakableSpace($content) {
  $content = preg_replace('/\s(!|\?|:)/m','&nbsp;$1',$content);
  return $content;
}   
?>

Non-breaking spaces will be added on title, content and ACF fields (only if ACF fiels use Wysiwyg Editor).

Submit a Comment

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