CodeMirror is a versatile JavaScript component that turns any HTML textarea into a full-featured code editor with out-of-the-box support for over 120 (programming) languages. It’s neither the first nor the only such component, but it’s the one that was added to the WordPress core in v4.9 to improve the code editing experience; specifically, syntax highlighting, linting, and code competition.
Code editing is necessary especially when you have a media-rich website or an e-commerce store with numerous products.
Live code editing is frowned upon by many, but it’s also used by even more users who need to do just a bit of tweaking on their site. That tweaking (and CodeMirror) is available in Appearance – Editor where you can edit theme files, in Plugins – Editor where you do the same with plugins, and in Customizer – Additional CSS. Since CodeMirror is available in the core and super-easy to add to any plugin or theme, we’ll have a look at how you can make your plugin better and more user-friendly with just a few lines of code.
Do I need this CodeMirror thing?
Programming languages now have become an essential part of any domain for development. Languages like HTML, CSS, JS, etc. are largely used. Python is one of the most versatile and preferable programming languages among developers. Data Science is the top trending technology that is widely used and people prefer to master it with various Data Science Online Courses.
If your plugin has any input fields where users enter code snippets, then you most surely need CodeMirror. Even if it’s just a few lines of custom CSS, the improvement in user experience that you’ll accomplish by turning a regular textarea field into a CodeMirror powered one is huge. The syntax highlighting alone makes a huge difference. It’ll also greatly reduce your support load as users will make less code-related mistakes which means a lower cost of maintaining the plugin. CodeMirror did wonders for our Htaccess Editor plugin.
It’s safe to assume most plugins and themes let users enter custom CSS code. Some let them add custom JavaScript and HTML, and only a few custom PHP code. That’s all fine as CodeMirror comes with built-in support for all those languages. No extra tinkering needed.
The HTML
It doesn’t matter where you’re adding CodeMirror to as it only requires enqueuing a few scripts, but for this article, we’ll assume it’s the settings screen of a plugin.
You probably already have a textarea in your plugin that you want to make fancy, so nothing needs changing there. Just make sure that it has an ID we can target.
echo '<textarea id="fancy-textarea">' . esc_textarea($val) . '</textarea>';
Enqueing JS & CSS and setting up
First, we’ll generate the editor settings and then send them over to our JS file with wp_localize_script()
. The wp_enqueue_code_editor()
function has quite a few options as you can see in the official documentation, but I doubt you’ll need any of them besides the “type” to define what kind of code is we’ll be editing. Use “text/css” for CSS and “text/javascript” for JavaScript code. We also need to enqueue the editor’s core CSS and JS files.
Please follow best practices and make sure you’re including these JS and CSS files only on admin screens where they’re needed. Either check the $hook
variable or use get_current_screen()
to determine on what admin page you’re on.
add_action('admin_enqueue_scripts', 'codemirror_enqueue_scripts'); function codemirror_enqueue_scripts($hook) { $cm_settings['codeEditor'] = wp_enqueue_code_editor(array('type' => 'text/css')); wp_localize_script('jquery', 'cm_settings', $cm_settings); wp_enqueue_script('wp-theme-plugin-editor'); wp_enqueue_style('wp-codemirror'); }
Init CodeEditor via JS
We still need to initialize the editor based on the settings prepared in the earlier step. This code goes into your plugin’s JS file that’s enqueued in the backend, on the settings page. It only has two params – one to target the appropriate element and the second with the settings generated in PHP.
jQuery(document).ready(function($) { wp.codeEditor.initialize($('#fancy-textarea'), cm_settings); })
Custom CSS
Everything works fine out-of-the-box, so there’s no need for custom CSS but if you’d like to get away from the default styling target the editor with something like this. Make sure you’re not targeting the textarea element as that won’t work anymore.
.CodeMirror { border: 1px solid #ddd; }
Using code components/modules/pieces that come with WP core is the preferred way of building plugins and themes. True, those components are rarely perfect but that’s a fair trade of for using tried-and-tested code that’s 100% compatible with WP core.
Using built-in scripts is the way to go
See how easy that was. Just a few lines of code and not only does the editor looks great, but it also has great useful features. Syntax highlighting and real-time error checking goes a long way in ensuring any code users enter is valid. And since users have already seen and used this code editor in WP admin the learning curve is virtually non-existent.
Excellent tip and tutorial. I just did the implementation in a plugin and I really liked the result.
Thanks for the tutorial, very helpful. It works like a charm.
I got error
jquery.min.js:2 Uncaught TypeError: Cannot read property ‘value’ of undefined
at Function.fg [as fromTextArea] (load-scripts.php?c=1&load[]=jquery-core,jquery-migrate,utils,wp-codemirror,underscore&ver=5.2.1:31)
at Object.b.codeEditor.initialize (code-editor.min.js?ver=5.2.1:1)
at HTMLDocument. (pg_custom_log.js:10)
at e (jquery.min.js:2)
at t (jquery.min.js:2)
Hi, sorry to hear you’re having problems 🙁 It’s very difficult to help just by looking at that error. Do you have the full source uploaded somewhere so we can check?
This works fine. How about the rest ? How can someone access the number of errors and list them somewhere? Does this document has another part ? if not it would be helpful if you are kind to mention it
Hi, have a look in the docs – https://codemirror.net/doc/manual.html#api
But I think you’ll need an addon to grab errors.
I have checked manual. WordPress has used the functions in the official manual. So using that again in plugin seems wasting the available resources.
Thanks for this great tutorial.
I am interested in how one would go about using codemirror for inbrowser editors for programming languages such as python, R and sql. Any ideas?
Hi Dan,
Just change the “type” to whatever you need (see code above). Here’s a list of supported types/ languages – https://codemirror.net/1/
Dear author,
Thank you for this guide! I’m looking for a way to save the custom added CSS to the front-end of the website. How can I achieve that?
Hi,
You should use the theme customizer for that. You can find it in the Appearance menu.
your article is superb i really like it keep spreading knowledge. u also learn about cloud computing go there thinkcloudly.com