Custom WordPress themes and plugins

How To Add Code Examples In WordPress

Logo for Prism JS

We recently came across the problem of including code examples in WordPress. To-date, the sites we have done have not been very technical or required any code to be displayed. Welcome to the joys of running a web development website!

We began by looking at the W3C recommendations for code examples on the code element page. The summary of this page is that all code examples should be wrapped in a <code> tag. That code tag should have a class of language- with the name of the language coming after the dash. Multi-line code examples should be wrapped in a <pre> tag. Here is an example:

<pre class="language-css"><code class="language-css">.strong {
	font-weight: bold;

Code Examples In WordPress Editor

The WordPress guide to writing code in your posts matches the W3C recommendations for using <pre> and <code> tags, but does not mention the use of classes to denote the language.

There are several issues with trying to include code examples in a WordPress post or page. Using the text tab in the WordPress editor will make it possible to enter the correct tags, however including a tab stop can be difficult. There are solutions out there to fix this, such as the Tabs in Post Editor plugin, or a jQuery solution you can add yourself. I prefer to use Notepad++ to format the text the way I want, and then copy+paste it into the WordPress editor. Keep in mind that switching between the visual and text tabs will strip all of the whitespace characters (tabs, extra break returns, and &nbsp; tags and spaces), unless they are contained within <pre> tags.

This works for everything except HTML code. This problem extends beyond WordPress, most syntax highlighters seem to strip HTML, and require special work-arounds to get this displaying correctly. We will look at some of these techniques as we go further into the post.

Of course all of this can be avoided by using an online service such as Pastebin, or JSFiddle, and simply including a link on the page to the code.

If you are a user of (i.e. you actually host your site through, and do not have a web host with installed), you can use the [code] shortcode – [code] shortcode. However, this did not match our needs, so I investigated for a method to display code examples in WordPress.

Available Syntax Highlight Libraries

We found several options to provide syntax highlighting that could be integrated with a website. Most are written using JavaScript and CSS, to correctly parse and style the content, however I did also find an online tool that will build the style in-line to the tag – Here are the syntax highlight libraries we found:

After reviewing the options, it seems like Prism JS would match our needs. It is widely supported, has the plugins we are looking for (line highlight, line numbers, etc), and has several plugins already available for quick integration into WordPress. Best of all, it follows W3C and WordPress recommendations, so if you have been writing syntactically correct code, adding this plugin will simply make it look better without any further edits.

Since we wanted to integrate Prism a bit more and set the options, we decided to add it directly to our theme. We’ll cover the steps on how to do that now.

Installing Prism In A Site

The first step is to head to the Prism Download page, set the options appropriate to your needs, and download the JavaScript and CSS files. Save these to the local computer, since we will need to add these files to the theme on the web server.

Screenshot of the Prism download page
Screenshot of Prism Download page

Prism Download Options

Unless you are planning on modifying the Prism library, or want to switch themes on a regular basis, you should get the Minified version as it will be smaller and quicker to load.

The Languages section will allow for different types of syntax highlighting, best practice would be to include only what you need, or may need in the future. Loading all of the languages will result in extra processing time for the server.

The Plugins can be very useful. Some require extra code to work properly. For example, the Line Numbers plugin requires an extra class in the <pre> tag – line-numbers. Select any plugins that should be included in the download.

Installing Prism Into The Theme

Once the files have been saved to your local computer, they are ready to add to your WordPress theme. This will involve editing the theme files themselves, as well as copying the Prism files up to the web server. Check the WordPress guide on using FileZilla if you are unsure how to do this.

Upload The Files To The Web Server

Once you are ready, connect to the FTP server and find the root of the website (you should see these three folders: wp-admin, wp-content, and wp-includes, see the WordPress guide on uploading files for more information). Browse in to the following folders: wp-content > themes, and find your theme folder. If you are unsure which one is correct, log in to the admin dashboard of your site, and click Appearance > Themes to see which theme your site is running. The folder name usually matches the theme name. Browse into the theme folder.

If you like to keep CSS and JavaScript files in their own separate folders, feel free to do so. However please make the necessary adjustments in the following examples if you decide to keep the files in a different place. Otherwise, it is safe to copy these files directly in to the theme folder. Make sure both of the Prism files are uploaded to the theme folder on the server.

Include The Files In Functions.php

Once that is completed, we need to edit the functions.php file. I’ll make a quick note about WordPress child themes here. If you purchased a theme, you should be making changes to a child theme of the purchased theme. If you are unsure how to set this up, you may want to contact the theme developer to see if they have a template available. Switching to a child theme is usually very quick and painless, and will mean that your changes will not be lost if you upgrade the theme at a later date. Not to mention the chances of breaking the site are reduced, and if everything goes downhill, you can always switch back to the main theme at a moments notice to get the site back up and running.

One last note, before you edit any files on a web server, you should always make a back up of the files beforehand. Copy the functions.php file to a safe place on your local computer, separate from the file we are about to edit. If things go wrong and the site has problems, upload the backed-up file to quickly restore the site.

Now, back to the functions.php file. Every WordPress theme will have this file (even child themes!) in the root of the theme folder. You can edit the file by finding it in FileZilla, right-clicking the file, and selecting edit, or by copying the file to the local computer, editing, and re-uploading to the server. Open the functions.php file by using one of these methods now.

Insert the following code into the functions.php file, near the bottom. If there is a ?> symbol at the bottom, that should always be the last element in the file. Copy the example above ?>. Otherwise feel free to place the code at the bottom of the file. Note: If you placed the Prism files into a different directory, now is the time to change the example to match the location of the files! Add the custom path into the string that contains the file name.

// function to add Prism files to this site
add_action( 'wp_enqueue_scripts', 'custom_prism_enqueue' );
function custom_prism_enqueue() {
	wp_enqueue_script('custom_prism_js', get_stylesheet_directory_uri() . '/prism.js');
	wp_enqueue_style('custom_prism_css', get_stylesheet_directory_uri() . '/prism.css');

Check the WordPress Codex page on wp_enqueue_scripts for an in-depth explanation of what is going on here, but suffice to say we are including the Prism files whenever anyone views the front of the site. This means if you have code examples wrapped in <pre> and <code> blocks, they will now be styled according to the theme you selected when you downloaded Prism. Synatx highlighting will also start working if you have any language- classes applied.

Make sure the edited functions.php is uploaded back into the theme folder to get this all working. If you used FileZilla to edit the file, you should be prompted once a change is detected. Otherwise the file will have to be manually uploaded. Congratulations, you should now have beautiful code examples on your site!
Screenshot of code examples in WordPress

Problems And Fixes

We ran into very few troubles while setting up Prism in our own site here. The main problems came from the Prism themes themselves, and trying to show HTML examples. The theme fixes involved small edits to the prism.css file. For instance, the Coy theme did not seem to provide in-line examples, like this one, it tried to break every code block on to its own line. To solve this problem, we changed the following code in the prism.css file.

Original Code

/* Inline code */
:not(pre) > code[class*="language-"] {
	position: relative;
	padding: .2em;
	-webkit-border-radius: 0.3em;
	-moz-border-radius: 0.3em;
	-ms-border-radius: 0.3em;
	-o-border-radius: 0.3em;
	border-radius: 0.3em;
	color: #c92c2c;
	border: 1px solid rgba(0, 0, 0, 0.1);

Modified Code

/* Inline code */
:not(pre) > code[class*="language-"] {
	position: relative;
	padding: 0 .2em;
	display: inline;
	-webkit-border-radius: 0.3em;
	-moz-border-radius: 0.3em;
	-ms-border-radius: 0.3em;
	-o-border-radius: 0.3em;
	border-radius: 0.3em;
	color: #c92c2c;
	border: 1px solid rgba(0, 0, 0, 0.1);

The padding attribute was modified, and the display attribute was added. The one side-affect of this edit was that code blocks not wrapped in pre tags can extend forever, so make sure any long examples are contained in <pre> tags!

Display HTML Code Examples

The HTML problem was more pervasive. Any HTML code is parsed as actual HTML code, even if it is contained in <pre> or <code> elements. HTML entities can also be troublesome, if you are actually trying to display the entity tag instead of the entity itself.

One simple solution is to replace one of the characters with an actual HTML entity. In the case of HTML code, the entity to replace is the < character before each opening and closing tag. The way to do this is to use the entity code &lt; instead of typing the actual < character. If you were to actually type this out in a code example, it would look like this:

<pre class="language-markup"><code class="language-markup">Use &lt;strong>strong&lt;/strong> to bold words,&lt;br>
and &lt;em>em&lt;/em> to italicize them.</code></pre>

It may look odd in code form, but if this example is copied and pasted into a web page, the browser will convert the special character code into the correct symbol, and others will be able to copy and paste the example without any issues.

The way to display an HTML entity is to use the &amp; instead of the actual & symbol. For instance:

The & entity can be displayed by typing &amp;

Here is the actual code to display this:

The &amp; entity can be displayed by typing &amp;amp;

As you can see, we had lots of fun adding code examples to our site. We may have gone a bit overboard, but my goal is to be as informative as possible. I hope our guide here has been helpful, and has been able to demonstrate how to properly display code examples in WordPress.