WordPress – How to automatically insert Non-Breaking Space using Ctrl + Shift + Space

A non-breaking space allows you to add a space between two words that prevents an automatic line break (line wrap) at its position.

They’re commonly used where amounts, such as dollars are separated using a space or when typing a brand name.

When using Microsoft Word it’s as easy as typing Ctrl + Shift + Space – but it’s not at easy in an HTML WYSIWYG editor such as in WordPress.

However, with the following PHP filter you can make TinyMCE automatically create a non-breaking space when using the Ctrl + Shift + Space key combination.

If you’re not sure where to place this code I highly recommend you read How to create a WordPress plugin for your custom functions.

function itsg_tinymce_nbsp( $settings ) {
$settings['setup'] = <<<JS
[function(editor) {
var down = {};
editor.onKeyDown.add( function( editor, event ) {
down[event.keyCode] = true;
});
editor.onKeyUp.add( function( editor, event ) {
if ( down[16] && down[17] && down[32] ) {
editor.execCommand( 'mceInsertContent', false, '&nbsp;' ); // inserts non-breaking space
}
down[event.keyCode] = false;
});

}][0]
JS;
$settings['entities'] = '160,nbsp,38,amp,60,lt,62,gt'; 
$settings['entity_encoding'] = 'named';
return $settings;
}
add_filter( 'tiny_mce_before_init', 'itsg_tinymce_nbsp' );

Tagged in

4 comments on “WordPress – How to automatically insert Non-Breaking Space using Ctrl + Shift + Space

  1. The code here inserts space + nbsp + space.

    Some changes to make it work as of June 2023:

    “`
    function itsg_tinymce_nbsp( $settings ) {
    $settings[‘setup’] = <<
    “`

  2. Hello Adrian,

    Many thanks for getting back in touch with me. I am sorry, but the code does not seems to work. If I press LEFT Shift, LEFT CTRL and the space bar, the ‘ ‘ is not entered. I do not see it when the editor is in the ‘text’ mode while the Shift, Ctrl and spacebar is entered in the ‘Visual’ mode.

    If I go to Plugins -> Plugin Editor -> Select plugin to edit -> itsupportguides.com custom function I see the text above in the black box.

    What can I do more to help you?

    With kind regards,
    TheStingPilot

  3. Hello,
    A very good idea. I have put your idea in action: created a file called itsg-custom-functions.php.

    I cannot post the content, but it is the same as above.

    Created a zip file, uploaded it, activated the plugin. And in TinyMCE the combination Left Shift – Left Ctrl and space does not create a non-breaking space.

    What is wrong?

    Thanks for your help.

    1. Hi TheStingPilot

      It looks like the filter works different now – resulting in the code not loading.

      I’ve updated the article with code that should work.

      Adrian

Leave a Comment

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