wp_enqueue_code_editor()WP 4.9.0

Connects all necessary (scripts, styles, settings, languages) for using the built-in code editor in WordPress.

For editing code in the textarea field, the library CodeMirror is used, starting from WP version 4.9.

What does the function do?

The function enqueues the following basic WP scripts and styles:

wp_enqueue_script( 'code-editor' );
wp_enqueue_style( 'code-editor' );

Then, based on the specified or determined type of code that will be used in the textarea, it may enqueue additional lint/hint scripts needed by CodeMirror. For example, for the HTML type, these additions will auto-close tags, provide hints, etc.

wp_enqueue_script( 'htmlhint' );
wp_enqueue_script( 'csslint' );
wp_enqueue_script( 'jshint' );

Next, based on the parameters passed to the function, it collects parameters for CodeMirror and replaces/augments the default parameters: wp.codeEditor.defaultSettings.

Filter wp_code_editor_settings

Plugins can filter CodeMirror parameters before they are merged with the defaults through the filter wp_code_editor_settings.

If the filter returns false, the function will not enqueue any scripts.

Disabling syntax highlighting

If syntax highlighting is disabled in the current user's options (Users > Profile), the function will do nothing and terminate its operation at the very beginning:

Global variable wp.codeEditor

When the CodeMirror script is enqueued, a global variable is not registered in JS to avoid conflicts if some plugin uses its own version of this library. The instance of the CodeMirror object is located in the variable wp.codeEditor. That is, you can write like this: window.CodeMirror = wp.CodeMirror.

The method initialize() - wp.codeEditor.initialize( id, options ) - is analogous to CodeMirror.fromTextArea(). The first argument takes an id or the textarea element object, and the second takes options for CodeMirror. Such options are returned by this function, but in the form of a PHP array.

Also, in the options for the initialize() method, you can specify additional callback functions: onChangeLintingErrors, onUpdateErrorNotice, onTabPrevious, onTabNext. These callbacks allow you to manage the display of lint error blocks and keyboard navigation (for hints).

Hooks from the function

Returns

Array|false. An array of settings for CodeMirror in PHP format.

Usage

$settings = wp_enqueue_code_editor( $args );
$args(array) (required)

Parameters.

  • type(string)
    MIME type of the file to be edited. For example: text/html, indicates that HTML code will be written in the editing field. Possible types:

    type language
    text/html html
    xml xml
    application/javascript javascript
    json json
    application/x-httpd-php php
    text/x-sql sql
    text/css css
    text/x-scss scss
    text/x-less less
    text/x-sass sass
    text/nginx nginx
    text/x-markdown markdown
    text/x-gfm gfm
    jsx jsx
    text/x-diff diff
  • file(string)
    An alternative to the $type parameter. The name of the file, for example file.php. Used to determine the type ($type) by the file extension.

  • codemirror(array)
    Allows you to directly specify parameters for CodeMirror. Will overwrite the current ones. The array has the same structure as if we were passing CodeMirror parameters in JS. See documentation.

  • csslint(array)
    Allows you to directly specify parameters for CSSLint. Will overwrite the current ones.

  • jshint(array)
    Allows you to directly specify parameters for JSHint. Will overwrite the current ones.

  • htmlhint(array)
    Allows you to directly specify parameters for HTMLHint. Will overwrite the current ones.

  • theme(WP_Theme)
    The theme being edited. For the theme file editing page.

  • plugin(string)
    The plugin being edited. For the plugin file editing page.

Examples

0

#1 Example of creating a code editor for textarea

To do this, let's turn the Biography field on the profile edit page into an HTML code editor.

To get a better idea of what the code does, let's look at the HTML code of the textarea, which will eventually become a code editor:

<textarea id="description" name="description" rows="5" cols="30"></textarea>
add_action( 'admin_enqueue_scripts', function() {

	if ( 'profile' !== get_current_screen()->id ) {
		return;
	}

	// connect the code editor for HTML.
	$settings = wp_enqueue_code_editor( array( 'type' => 'text/html' ) );

	// do nothing if CodeMirror is disabled.
	if ( false === $settings ) {
		return;
	}

	// initialization
	wp_add_inline_script( 
		'code-editor',
		sprintf( 'jQuery( function() { wp.codeEditor.initialize( "description", %s ); } );', wp_json_encode( $settings ) )  
	);

} );

The result is:

The variable $settings contains such an array:

Array
(
	[codemirror] => Array
		(
			[indentUnit] => 4
			[indentWithTabs] => 1
			[inputStyle] => contenteditable
			[lineNumbers] => 1
			[lineWrapping] => 1
			[styleActiveLine] => 1
			[continueComments] => 1
			[extraKeys] => Array
				(
					[Ctrl-Space] => autocomplete
					[Ctrl-/] => toggleComment
					[Cmd-/] => toggleComment
					[Alt-F] => findPersistent
					[Ctrl-F] => findPersistent
					[Cmd-F] => findPersistent
				)

			[direction] => ltr
			[gutters] => Array
				(
					[0] => CodeMirror-lint-markers
				)

			[mode] => css
			[lint] => 1
			[autoCloseBrackets] => 1
			[matchBrackets] => 1
		)

	[csslint] => Array
		(
			[errors] => 1
			[box-model] => 1
			[display-property-grouping] => 1
			[duplicate-properties] => 1
			[known-properties] => 1
			[outline-none] => 1
		)

	[jshint] => Array
		(
			[boss] => 1
			[curly] => 1
			[eqeqeq] => 1
			[eqnull] => 1
			[es3] => 1
			[expr] => 1
			[immed] => 1
			[noarg] => 1
			[nonbsp] => 1
			[onevar] => 1
			[quotmark] => single
			[trailing] => 1
			[undef] => 1
			[unused] => 1
			[browser] => 1
			[globals] => Array
				(
					[_] => 
					[Backbone] => 
					[jQuery] => 
					[JSON] => 
					[wp] => 
				)

		)

	[htmlhint] => Array
		(
			[tagname-lowercase] => 1
			[attr-lowercase] => 1
			[attr-value-double-quotes] => 
			[doctype-first] => 
			[tag-pair] => 1
			[spec-char-escape] => 1
			[id-unique] => 1
			[src-not-empty] => 1
			[attr-no-duplication] => 1
			[alt-require] => 1
			[space-tab-mixed-disabled] => tab
			[attr-unsafe-chars] => 1
		)

)

JS function wp.codeEditor.initialize(textarea, settings)

Located in the file wp-admin/js/code-editor.js

Parameters:

textarea(string|jQuery|Element) (required)
The id attribute of the element as a string, a jQuery element, or a DOM element of the textarea field for which the editor will be used.
settings(object) (required)

JS object of settings for codeMirror. This function returns it as a PHP array: wp_enqueue_code_editor().

What can be specified in the object:

  • settings.onChangeLintingErrors(Function) - Callback when linting errors change.
  • settings.onUpdateErrorNotice(Function) - Callback for when the error notice should be displayed.
  • settings.onTabPrevious(Function) - Callback for handling TAB key to the previous element.
  • settings.onTabNext(Function) - Callback for handling TAB key to the next element.
  • settings.codemirror(object) - CodeMirror options.
  • settings.csslint(object) - CSSLint rules.
  • settings.htmlhint(object) - HTMLHint rules.
  • settings.jshint(object) - JSHint rules.

Looks like this:

{
	"codemirror": {
		"indentUnit"      : 4,
		"indentWithTabs"  : true,
		"inputStyle"      : "contenteditable",
		"lineNumbers"     : true,
		"lineWrapping"    : true,
		"styleActiveLine" : true,
		"continueComments": true,
		"extraKeys": {
			"Ctrl-Space" : "autocomplete",
			"Ctrl-/"     : "toggleComment",
			"Cmd-/"      : "toggleComment",
			"Alt-F"      : "findPersistent",
			"Ctrl-F"     : "findPersistent",
			"Cmd-F"      : "findPersistent"
		},
		"direction": "ltr",
		"gutters": [
			"CodeMirror-lint-markers"
		],
		"mode"              : "css",
		"lint"              : true,
		"autoCloseBrackets" : true,
		"matchBrackets"     : true
	},
	"csslint": {
		"errors"                    : true,
		"box-model"                 : true,
		"display-property-grouping" : true,
		"duplicate-properties"      : true,
		"known-properties"          : true,
		"outline-none"              : true
	},
	"jshint": {
		"boss"    : true,
		"curly"   : true,
		"eqeqeq"  : true,
		"eqnull"  : true,
		"es3"     : true,
		"expr"    : true,
		"immed"   : true,
		"noarg"   : true,
		"nonbsp"  : true,
		"onevar"  : true,
		"quotmark": "single",
		"trailing": true,
		"undef"   : true,
		"unused"  : true,
		"browser" : true,
		"globals": {
			"_"        : false,
			"Backbone" : false,
			"jQuery"   : false,
			"JSON"     : false,
			"wp"       : false
		}
	},
	"htmlhint": {
		"tagname-lowercase"       : true,
		"attr-lowercase"          : true,
		"attr-value-double-quotes": false,
		"doctype-first"           : false,
		"tag-pair"                : true,
		"spec-char-escape"        : true,
		"id-unique"               : true,
		"src-not-empty"           : true,
		"attr-no-duplication"     : true,
		"alt-require"             : true,
		"space-tab-mixed-disabled": "tab",
		"attr-unsafe-chars"       : true
	}
}

Notes

Changelog

Since 4.9.0 Introduced.

wp_enqueue_code_editor() code WP 6.9.1

function wp_enqueue_code_editor( $args ) {
	if ( is_user_logged_in() && 'false' === wp_get_current_user()->syntax_highlighting ) {
		return false;
	}

	$settings = wp_get_code_editor_settings( $args );

	if ( empty( $settings ) || empty( $settings['codemirror'] ) ) {
		return false;
	}

	wp_enqueue_script( 'code-editor' );
	wp_enqueue_style( 'code-editor' );

	if ( isset( $settings['codemirror']['mode'] ) ) {
		$mode = $settings['codemirror']['mode'];
		if ( is_string( $mode ) ) {
			$mode = array(
				'name' => $mode,
			);
		}

		if ( ! empty( $settings['codemirror']['lint'] ) ) {
			switch ( $mode['name'] ) {
				case 'css':
				case 'text/css':
				case 'text/x-scss':
				case 'text/x-less':
					wp_enqueue_script( 'csslint' );
					break;
				case 'htmlmixed':
				case 'text/html':
				case 'php':
				case 'application/x-httpd-php':
				case 'text/x-php':
					wp_enqueue_script( 'htmlhint' );
					wp_enqueue_script( 'csslint' );
					wp_enqueue_script( 'jshint' );
					if ( ! current_user_can( 'unfiltered_html' ) ) {
						wp_enqueue_script( 'htmlhint-kses' );
					}
					break;
				case 'javascript':
				case 'application/ecmascript':
				case 'application/json':
				case 'application/javascript':
				case 'application/ld+json':
				case 'text/typescript':
				case 'application/typescript':
					wp_enqueue_script( 'jshint' );
					wp_enqueue_script( 'jsonlint' );
					break;
			}
		}
	}

	wp_add_inline_script( 'code-editor', sprintf( 'jQuery.extend( wp.codeEditor.defaultSettings, %s );', wp_json_encode( $settings, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ) ) );

	/**
	 * Fires when scripts and styles are enqueued for the code editor.
	 *
	 * @since 4.9.0
	 *
	 * @param array $settings Settings for the enqueued code editor.
	 */
	do_action( 'wp_enqueue_code_editor', $settings );

	return $settings;
}