How to Display Code on Your WordPress

If you run a development website, project documentation, product help section or anything similar from a WordPress website, chances are you’ve needed to display code at one time or another. Depending on the language used this can be a small pain or a really big pain.

In this Weekend WordPress Project, I’ll explain why this is such a bother and explore some of the options you have for displaying code beautifully and easily on your WordPress site.

Why Displaying Code is Difficult

To understand why displaying code is difficult you need to know some basic HTML. The code for making some bold text is to surround it in a tag. To create the bold text in that sentence I actually wrote <strong>bold text</bold> into my WordPress editor.

WordPress code
Showing code on your site can be tricky if you don’t know how.

So far so good, but now for the hard part: What if I want to show you how I did it?

Any time I type <strong> into the editor it gets interpreted as HTML code, which means it will disappear and instead be used to embolden the text.

The other problem that we have is syntax highlighting. Even if the code is displayed correctly it may be difficult to read without the correct styling.

Making Code Show Up

The best way to make code show up is to convert characters with a special meaning to HTML entities. You may already be aware that sometimes you’ll need to type &amp; instead of just a regular ampersand to make it show up properly. This is because &amp; is the HTML entity for the ampersand sign.

HTML entities are not interpreted as code but display just like their non-entity counterparts. In order to show me how to create bold text you would need to type:

1
&lt;strong&gt;bold text&lt;/bold&gt;
view raw bold.html hosted with ❤ by GitHub

&lt; is the HTML entity for the lower than sign (hence the lt) and &gt; is the HTML entity for the greater than sign – hence the gt.

Adding Code to a WordPress Post the Simple Way

The simplest way to add code to your posts is to use the HTML entities and wrap everything in <pre> tags. This tag is for displaying code and most themes will contain appropriate styling. A quick example of what I mean, straight out of a post:

1 2 3 4 5 6 7
To add the motivation text to the top area, simply hook a function into admin_notices, like so:
<pre>add_action( ‘admin_notices’, ‘show_mot_text’ );
function show_mot_text() {
$text = get_motivation_text();
echo “&lt;p id=’wp-admin-motivation’&gt;$text&lt;/p&gt;“;
}</pre>
view raw code-simple.html hosted with ❤ by GitHub

Note that I started the code right after the opening tag and I wrote the closing tag right after the last character of code. It would be cleaner to put these on new lines but many Javascript syntax highlighters will interpret these line breaks as actual line breaks. Thus, it is a good idea to get into the habit of not leaving line breaks here.

This works just fine but it is a nightmare to maintain. If you have a lot of tags in there, not just the odd paragraph it becomes a jumble of HTML entities making it very difficult to edit the code. If I need to resort to this method I actually use my text editor to create the HTML entities.

I write normal code and then use my text editor to convert all HTML entities all at once. If you need to modify the code you can paste the converted version and decode them into their proper characters. If you use Atom.io you can use the HTML Entities package, if you use Sublime you can use the HTML: Encode Special Characters command.

Even if you get a good workflow going it just looks so unruly in the WordPress post editor and – let’s face it – this is far from a quick workflow.

A Better Code Workflow

A better way to add code to a website is to use a plugin for this very purpose. Many plugins use a Javascript component to add syntax highlighting and other options to your code. My favourite syntax highlighter is Prism and luckily, there’s a plugin that incorporates it into WordPress.

Grab Prism WP, install it and start writing code, following the guidelines below.

  • Wrap your code in <pre> and <code> tags as well
  • The code may receive a special class which designates the target language, this is used for highlighting
  • If you’d like line numbers you need to enable this in the plugin settings and add the line-numbers class to the pre element.

Our code example above now looks like this in the code editor:

1 2 3 4 5
<pre class=line-numbers><code class=language-php>add_action( ‘admin_notices’, ‘show_mot_text’ );
function show_mot_text() {
$text = get_motivation_text();
echo “<p id=wp-admin-motivation>$text</p>”;
}</code></pre>
view raw code-prism.html hosted with ❤ by GitHub

That looks much better doesn’t it? It has a lovely output as well, by default it looks like the screnshot below When using the Twenty Fifteen theme.

Prism Highlighter Output
Prism Highlighter Output

There are a number of other themes you can use, take a look on the Prism homepage. Themes can be changed in the right with the round thingies. The plugin allows you to change the theme in the settings of the plugin.

External Services

There are tons of services which allow you to paste your code such as Gist, JSFiddle and Pastebin. Each of these services has WordPress plugins that allow you to embed them into WordPress posts, like we do here at WPMU DEV with Gists.

I recommend going to the plugins search page on WordPress and searching for your preferred provider, you’ll find a great plugin in seconds.

DIY

I always like to come up with DIY solutions to problem, so let’s try and do some of this for ourselves. Let’s not get into the whole highlighting area – which is really very complex – but we can do a lot to make code insertion a lot easier in WordPress.

The biggest issue we face is the HTML entities problem. What we’d like is to write code as-is on the backend and get it to display as-is on the front-end as well without being interpreted as tags. The way we can do this is by adding a filter to the_content.

The idea is that before the content is displayed we’ll look through our content for any text within code tags and replace all the special characters in it with HTML entities.

I actually wrote a tiny plugin named Smart Code Escape to do just that a few months back. It’s a perfect example of something useful that uses all of 15 lines of code. Let’s take a look now.

The first thing you’ll want to do is create a plugin. We have a handy creating a plugin guide for you if you don’t know how.

In a nutshell: Create a folder in your plugins directory named smart-code-escape and a file within that folder named smart-code-escape.php. Add the following content to the file, I’ll explain everything in a moment.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
<?php
/*
* Plugin Name: Smart Code Escape
* Plugin URI: https://github.com/danielpataki/Smart-Code-Escape
* Description: Converts less than, greater than and ampersand characters to their HTML
entities within pre tags before they are output on the page. You will always see the
non-escaped version in the editor, making code easy to modify. It Will not convert code
tags directly within pre tags to support Prism-style highlighting.
* Version: 1.1
* Author: Daniel Pataki
* Author URI: http://danielpataki.com
* License: GPL v2
* Licence URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
function smart_code_escape_pre( $data ) {
preg_match(@(<code.*>)(.*)(<\/code>)@isU, $data[2], $matches );
if( !empty( $matches ) ) {
return $data[1] . $matches[1] . str_replace( array( &, <, > ), array( &amp;, &lt;, &gt; ), $matches[2] ) . $matches[3] . $data[3];
}
else {
return $data[1] . str_replace( array( &, <, > ), array( &amp;, &lt;, &gt; ), $data[2] ) . $data[3];
}
}
add_filter( the_content, smart_code_escape_content, 9 );
function smart_code_escape_content( $content ) {
$content = preg_replace_callback(@(<pre.*>)(.*)(<\/pre>)@isU, smart_code_escape_pre, $content );
return $content;
}
view raw sce.php hosted with ❤ by GitHub

The actual plugin has inline code documentation, if you’re interested download it from the repository and take a look. The first thing to notice is that I’ve added a filter to the_content. This filter calls a callback function on content found between <pre> tags.

The callback function (smart_code_escape_pre()) takes care of the conversion. It checks if the content is wrapped in a <code> tag first. I thought I’d add this to make sure the plugin doesn’t conflict with existing code plugins like the Prism one I mentioned earlier. I assume that if someone adds their code by wrapping it in a <pre> and a <code> tag they’re serious about code insertion and have a system in place already.

If the contents of the <pre> tag is not in a code block the function replaces all special characters with their HTML entities.

Conclusion

As you can see, adding code to your website is not that difficult, you just need to know the basics of why characters get encoded and you’re all set.

If you have some great ways of adding code to your website let us know in the comments below.