Advertisement
Creative Coding

Making the WordPress Editor Look Pretty Using CodeMirror

by

WordPress contains two built-in editors that allow you to edit theme files directly from within the browser, they the Theme Editor and Plugin Editor. By default, the editor looks very simple, and hard to edit because the colors are totally black and grey. In this tutorial, I will show you how to integrate CodeMirror.js into the editors to make the look prettier. Our code snippets will be highlighted with more color, the editors will even have line numbers, and more.


Step 1 Preparing

First of all, you need to download the CodeMirror library. It is a powerful library, and supports many programming languages and features. After downloading and extracting, let's place this directory into your theme's directory (I use Twenty Eleven as a demo) and name it codemirror.

Then, we create a file called codemirror.php inside this directory and include this file in the functions.php file of your theme.

// functions.php
include("codemirror/codemirror.php");

Open our codemirror.php and move to the next step.

"CodeMirror is a JavaScript component that provides a code editor in the browser. When a mode is available for the language you are coding in, it will color your code, and optionally help with indentation."


Step 2 Register Scripts and Styles

add_action('load-theme-editor.php', 'codemirror_register');
add_action('load-plugin-editor.php', 'codemirror_register');

function codemirror_register() {

	wp_register_script('codemirror', get_template_directory_uri()."/codemirror/lib/codemirror.js");
	wp_register_style('codemirror', get_template_directory_uri()."/codemirror/lib/codemirror.css");

	wp_register_style('cm_blackboard', get_template_directory_uri()."/codemirror/theme/blackboard.css");

	wp_register_script('cm_xml', get_template_directory_uri()."/codemirror/xml/xml.js");
	wp_register_script('cm_javascript', get_template_directory_uri()."/codemirror/javascript/javascript.js");
	wp_register_script('cm_css', get_template_directory_uri()."/codemirror/css/css.js");
	wp_register_script('cm_php', get_template_directory_uri()."/codemirror/php/php.js");
	wp_register_script('cm_clike', get_template_directory_uri()."/codemirror/clike/clike.js");

	add_action('admin_enqueue_scripts', 'codemirror_enqueue_scripts');
	add_action('admin_head', 'codemirror_control_js');
}

Above snippets will hook the codemirror_register function into two hooks, load-theme-editor.php and load-plugin-editor.php. It means when the Theme Editor or Plugin Editor is requested, they will call our codemirror_register function.

Core Library

Inside this function, we register all needed script and style files. codemirror.js and codemirror.css are two main components of the CodeMirror library, they are in the lib directory.

Theme

blackboard.css is a theme file, the theme directory in the CodeMirror library also has many other theme files, you can change depending on your preferences. There are more available themes, see them here:

  • Default:
  • Blackboard:

Mode

Modes are JavaScript programs that help color (and optionally indent) text written in a given language. Their value is a MIME type value, these depend on the language we work with. You can see all modes in the mode directory within the CodeMirror library. Because WordPress' built-in Editor can edit HTML, PHP, CSS (more here), so I register theses scripts on the next lines of codemirror_register function. The reason why I've registered XML and Clike scripts will be explained later.

After registering all script files, we have to enqueue them every time our admin section loads. So I add the codemirror_enqueue_scripts function to the admin_enqueue_scripts hook. Then we also embed a control javascript file (we can modify, add or delete options script) of CodeMirror to admin head.


Step 3 Enqueue Scripts

function codemirror_enqueue_scripts() {
	wp_enqueue_script('codemirror');
	wp_enqueue_style('codemirror');

	wp_enqueue_style('cm_blackboard');

	wp_enqueue_script('cm_xml');
	wp_enqueue_script('cm_javascript');
	wp_enqueue_script('cm_css');
	wp_enqueue_script('cm_php');
	wp_enqueue_script('cm_clike');
}

The above function has no big issue to explain, it just enqueues all scripts that we registered earlier. Open the Theme Editor and view source and you will see these scripts were embedded in the header.


Step 4 Hook Up Script

Overview Usage

Basically, our script is:

function codemirror_enqueue_scripts() {
?>
	<script type="text/javascript">
		jQuery(document).ready(function() {
			var editor = CodeMirror.fromTextArea(document.getElementById("newcontent"));
		})
	</script>
<?php
}

This function will be embedded in the admin head section, CodeMirror will effect any element that contains the newcontent ID, because our textarea element that holds our code snippets has this ID.

When using CodeMirror without any options, CodeMirror will use its own default options. For more using more options, we can do so like this:

function codemirror_enqueue_scripts() {
?>
	<script type="text/javascript">
		jQuery(document).ready(function() {
			var editor = CodeMirror.fromTextArea(document.getElementById("newcontent"), {
				lineNumbers: true,
				mode: "text/javascipt",
				theme: "blackboard"
			});
		})
	</script>
<?php
}

Those additional options will make our editor have line numbers and the blackboard theme. Notice in the mode option, this option will determine what mode CodeMirror should use (In step 2, we mentioned what mode is). Because each file type has its own mode, we have to define this option to make CodeMirror work fine and display more accurately. Below are some MIME type values:

  • "text/javascript" for JavaScript mode
  • "text/css" for CSS mode
  • "application/x-httpd-php" for PHP mode, this mode require XML, JavasScript, CSS and C-Like modes. That is the reason we must register XML and C-Like scripts above.

Simple HTML/PHP mode based on the C-like mode. Depends on PHP, XML, JavaScript, CSS, and C-like modes. (see here)

Advanced Usage

For best usage, we need to define what file type we're editing to use the correct mode. Our goal is to make the script use the right mode automatically. Here is a solution:

function codemirror_control_js() {
	if (isset($_GET['file'])) { // $_GET['file'] holds path of file we edit
		$filename_to_edit = end(explode("/", $_GET['file'])); // We need to get file name
		$file = substr($filename_to_edit, stripos($filename_to_edit, '.')+1); // Get file extension
		switch ($file) {
			// And assign appropriate MIME type value to $file variable
			case "php": $file = "application/x-httpd-php"; break;
			case "js" : $file = "text/javascript"; break;
			case "css": $file = "text/css"; break;
		}
	}
	else {
		$file_script = $_SERVER['SCRIPT_NAME'];
		$file_script = end(explode('/', $file_script));
		if ($file_script == 'theme-editor.php')
			$file = "text/css";
		else
			$file = "application/x-httpd-php";
	}

	?>
	<script type="text/javascript">
		jQuery(document).ready(function() {
			var editor = CodeMirror.fromTextArea(document.getElementById("newcontent"), {
				lineNumbers: true,
				mode: "<?php echo $file ;?>",
				theme: "blackboard"
			});
		})
	</script>
	<?php
}

Every time we click on a file to edit it, the $_GET['file] variable will hold the path to that file. For example:

  • wp-admin/theme-editor.php?file=header.php

  • wp-admin/theme-editor.php?file=style.css

  • wp-admin/plugin-editor.php?file=akismet.php

And these code snippets will help us to define file extensions that we're editing:

	$filename_to_edit = end(explode("/", $_GET['file'])); // We need to get file name
	$file = substr($filename_to_edit, stripos($filename_to_edit, '.')+1); // Get file extension

Then depending on each extension, we assign a different MIME type value for that match.

Except for the first time we open the Theme or Plugin Editor, we don't click on any file to edit so the $_GET['file'] variable doesn't exist. WordPress will open a default file to edit automatically. For the Theme Editor, the default file is the style.css file and another PHP file in the Plugin Editor. So we need to define the MIME type value as "text/css" in the Theme Editor and "application/x-httpd-php" in the Plugin Editor.

Styling

Everything's done but the editor looks messy. We need to modify the CSS file a little. In the lib directory, we open the codemirror.css file, find below code snippets:

.CodeMirror-scroll {
	overflow-x: auto;
	overflow-y: hidden;
	height: 300px;
	/*
	 This is needed to prevent an IE[67] bug where the scrolled content
	 is visible outside of the scrolling box.
	*/
	position: relative;
	outline: none;
}

Replace with:

.CodeMirror, .CodeMirror div {
	margin-right: 0!important;
}
.CodeMirror-scroll {
	overflow-x: auto;
	overflow-y: hidden;
	height: 450px;
	/*
	 This is needed to prevent an IE[67] bug where the scrolled content
	 is visible outside of the scrolling box.
	*/
	position: relative;
	outline: none;
}

Your Turn

CodeMirror has many features, it is a really powerful javascript library. Read CodeMirror's manual for getting fully informed on the features available. You can find out the other features or how to customize them, and add to your WordPress code yourself. It's quite easy: register, enqueue and hook up the script, like the way I've done above.


Conclusion

In this tutorial, I don't focus too much on CodeMirror and its features, I just demonstrate the way to integrate it into the WordPress Editor to make our Editor look prettier or easy to work with. Hope this tutorial was useful for everybody.

If you think my tutorial has any problem, or you have better ideas, or something to add, leave your comments below! We would very much appreciate it.

Related Posts
  • Code
    Theme Development
    How to Pass PHP Data and Strings to JavaScript in WordPressPhp js 400
    It's good practice to put all your data in static strings in your PHP files. If you need to use some data in JavaScript later on, it's also good practice to put your data as data-* attributes in your HTML. But in some certain scenarios, you have no choice but to pass strings directly to your JavaScript code. If you are including a JavaScript library, and you've found yourself initializing a JavaScript object inside your header.php then assigning data to its properties, then this article is for you. This article will teach you on how to properly pass PHP data and static strings to your JavaScript library.Read More…
  • Code
    Creative Coding
    Adding Custom UI Themes to Wordpress Admin Using SassPreview image@2x
    With the release of WordPress 3.8 we now have a new feature for Admin UI themes. This means that every user can change the color scheme of his admin regardless of the the theme that’s being used on the front-end. To change the color scheme of your admin, go to Users > Your Profile. Here you’ll see eight predefined themes that you can select from. Select any theme from these themes and you’ll see the changes immediately. When you are done with selecting the theme, hit the “Update Profile” button.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Cheat Sheets
    The Complete Guide to Proper JavaScript Usage With WordPressJavascript 400
    I remember thinking "What the heck do we need JavaScript for, when we have Flash?" when I was fourteen. Although I still remember how I enjoyed coding stuff with ActionScript 2.0 back then, I saw how much one can achieve with JavaScript and fell in love with it. I'm not an expert on JavaScript (yet) but I can say I'm over and done with Flash for a long time. When it comes to WordPress, the biggest blogging platform and content management system worldwide, JavaScript is - of course - very useful for many things: content sliders, lightbox galleries, slick shopping carts, UI elements like tabs or accordions... you name it. But how exactly should we use JavaScript with WordPress? Returning or echoing a bunch of HTML script elements is one way to do it - and it's wrong. In this tutorial, we're going to see how to enqueue JavaScript files inside our pages and how to pass translatable data to the JavaScript code.Read More…
  • Code
    Theme Development
    Adding a Custom CSS Editor to Your Theme Using ACEAdding a custom css editor to your theme using ace
    Whenever someone downloads your theme and decides that some of the CSS isn't working for them, they usually go into style.css and manually modify the stylesheet to their liking. This isn't too hard to do, but it does present an issue when the next release of your theme is available and they decide to update. All of their changes will then be overwritten. A great work-around is to offer a Custom CSS editor so that all the changes they make will be safely stored in the database and keeping up to date in the future will not be an issue.Read More…
  • Code
    Tips
    Common WordPress Development Mistakes and How to Fix ThemCommon wordpress development mistakes and how to fix them
    With WordPress becoming more and more popular there is a massive amount of code being generated by users, agencies and marketplaces. I've been working with WordPress for a long time and it amazes me how many developers out there are making the same mistakes over and over again. I'm going to go through some of the most common development mistakes and how you can easily fix them, and going forward make your code better!Read More…