WordPress – How to make tab key create tabs in TinyMCE WYSIWYG editor

The following code will make the WordPress visual editor (TinyMCE) create “tabs” (which don’t actually exist in HTML, so we’re actually adding in two HTML entities for space).

With this code added when you click the tab button on the keyboard a the content will be automatically spaced out, as it would with a real tab in a document editor like Microsoft Word.

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.

add_filter( 'tiny_mce_before_init', function( $initArray ) {
  $initArray['setup'] = <<<JS
[function(editor) {
 editor.onKeyDown.add(function(editor, event) {
 if ( 9 == event.keyCode ) { // tab pressed
 editor.execCommand( 'mceInsertContent', false, '&emsp;&emsp;' ); // inserts tab
 event.preventDefault();
 return false;
 }
 });

}][0]
JS;
  return $initArray;
});

 

Related Articles

3 comments on “WordPress – How to make tab key create tabs in TinyMCE WYSIWYG editor

  1. If we would like the tab to be 25px do you have any tips for that as well? Also, I do not think this is a tab as used in Microsoft Word as there the tab becomes shorter if text occupies the area the tab is in. That is why some tabs are shorter than others. You can see this by showing hidden characters, or simply by looking at the space between a word in first tab area and the next. Any idea if solutions were created for that yet?

  2. Adding that filter to functions.php actually produces an error and stops the site from functioning.

    *Parse error: syntax error, unexpected ‘$initArray’ (T_VARIABLE)*

Leave a Reply

Your email address will not be published.