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;
});

 

Was this article helpful?

Related Articles