Display Code Snippets In WordPress

If you want to talk about programming or development in your WordPress post then there will be times when you want to write about code but make sure that the code doesn't behave like code would normally do in a web page. But you would still want the code to look just like it would look in a normal editor.

It is also important for any of your visitors to be able to copy and paste your code into their own application.

How WordPress Editor Handles Code

It depends on what text editor type in WordPress you use but you will have to do different things. If you use the Visual editor then WordPress will automatically convert characters like > and < into the HTML format &lt ; and &gt ;.

If you use the HTML editor then if you want to display a > or a < then you will need to type in &l t; and &g t; in your editor. There may be times when you want to paste a large chunk of code in your editor...if you use the visual editor WordPress may encode other parts of your code. If you use the HTML editor then you will have to go through all your code and manually change the > tags to &g t;.

Types Of Displaying Code

In your post there will be two ways you want to display your code, this will be either within a paragraph or in a block of code by itself.

If you want to display code inside a paragraph then you can use the <code> tag. This will tell the browser that the text inside the tag is computer code and will display the text as plain text.

For blocks of code and keeping the same format in your text you will need to use the <pre> tag.

The pre tag will not make your code look good so we can style this later but it will allow you to display the code correctly on the screen.

Quotes In Code

Wordpress has functionality that will convert your quotes to pretty quotes. These are quotes which you will normally find in Word processors, they make your quotes curly and look better in your text.

But if you are typing code into your text editor then it will make the code invalid for people copying the code. In code your quotes need to be straight quotes or they will not format correctly.

If you use a <pre> tag then you will not get this problem with quotes but if you are just display inline code by using the code tag the quotes will not be displayed correctly.

The two options you have is to use a pre tag or to encode the quotes manually by using & #34; for double quotes or & #39; for single quotes.

Creating A Shortcode Plugin

On Paulund I display a lot of code snippets, which is done by a plugin to create a shortcode.

In this article I will show you the plugin I use to do this and will teach you how to do the same thing.

I like using the HTML editor this is because I get to see exactly what the HTML is going be put into the posts, I can make sure that all the HTML on the page is clean. The problem I have is that when I copy a large amount of code into the editor, the editor will think this is actually HTML code and will display it as HTML not text.

In the past I used a WordPress plugin called syntax highlighter, this is a very good plugin which will allow you to easily display code using shortcodes, then depending on your shortcode it will display the code correctly as you would see in a normal code editor.

I really liked the idea of using shortcodes to define where the code was and used syntax highlighter for a very long time. But I always had a problem with it and that was the amount of CSS and JavaSscript it would add to the page there would be multiple files added to the page just to style the code. I wanted to just use CSS in my stylesheet to display the code and reducing the amount of the extra CSS and JavaScript files each page had to add. The only way I could do this is to create my own WordPress plugin to display the code.

As I really liked the idea of using a shortcode to display the code in the editor I copied this idea on my plugin, I am basically going to create a cut down, simpler version of syntax highlighter.

Defining The Plugin

To start the plugin we first need to define that this file is a plugin by using the following comments at the top of the WordPress plugin.

<?php
/*
 * Plugin Name: Paulund Syntax Highlighter
 * Plugin URI: http://www.paulund.co.uk
 * Description: A plugin that allows you to display code on your Website
 * Version: 1.0
 * Author: Paul Underwood
 * Author URI: http://www.paulund.co.uk
 * License: GPL2 

    Copyright 2012  Paul Underwood

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation. 

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
*/

Creating The Shortcodes

We are going to create shortcodes for the different languages of code to display. I have decided to use 4 shortcodes one for HTML, one for CSS, one for Javascript and one for PHP.

The reason why I am using 4 shortcodes is that if you want to style each of these differently you can. But for this example we are going to use the same function for all codes.

Once we have defined which languages we want to use then we can loop through these and create a shortcode by using the function add_shortcode().

/**
* Define the different language shortcodes
*/
$language = array("html", "css", "javascript", "php");

/**
* Create the different shortcodes
*/
foreach($language as $lang){
	add_shortcode( $lang, 'paulund_highlight_code' );	
}

Highlight Code Function

When the shortcode is used in the post it will run the function paulund_highlight_code(), as this is from a shortcode it will send two parameters to the function, attributes and content.

The attributes are data you can apply to the shortcode by using attributes, this can be used in the function called by the shortcode. The content parameter is the content that is placed inside the shortcode this is what we need to change to make WordPress display the code correctly.

It starts off by comparing the content to a strip tag version of the content if they are the same then we don't need to make any changes to the content, but if they are different then we will need to start the encoding.

For the encoding we start off by removing the paragraph tags and the line breaks, we need to do this as when the content is saved WordPress will automatically add in paragraphs and line breaks from the text editor. If we keep these tags in the content then when we wrap the code in a pre tag we will display the paragraph tags on the page.

Next we convert all < to

& lt;

and change > to

& gt;

. This is so the tags will display correctly on the page.

Lastly we can then wrap all the content around a pre tag and a code tag and return the content in the function. This will then output all your code correctly on the page and inside pre and code tags.

/**
* Change the content of the shortcode to display code in the content
*
* @param $atts - Shortcode Attributes
* @param $content - Content inside the shortcode
*/
function paulund_highlight_code($atts, $content = null){
	
	$encode = false;
	
	if($content != strip_tags($content)){
		$encode = true;
	}
	
	if($encode){
	
		$remove_array = array("&lt;p&gt;", "&lt;/p&gt;", "&lt;br /&gt;", "&lt;br/&gt;");
		$content = str_replace($remove_array, "", $content);
		
		$content = str_replace("<", "&lt ;", $content);
		$content = str_replace(">", "&gt ;", $content);
	}
		
	$content = "<pre><code>" . trim($content) . "</code></pre>";
	
	return $content;
}

Stop WordPress Converting Quotes To Pretty Quotes

The problem about doing this conversion at runtime is that WordPress will display your quotes as pretty quotes and not straight quotes which your code needs.

To stop WordPress from changes these quotes to the pretty quotes add the following lines to the top of the plugin.

remove_filter('the_content', 'wptexturize');
remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');

Finished Plugin

That's all the code you need to automatically add pre tags around the content.

This is what the finished plugin will look like you can now copy and paste this into a PHP file and upload this to your wp-content/plugins folder to use on your own website.

<?php
/*
 * Plugin Name: Paulund Syntax Highlighter
 * Plugin URI: http://www.paulund.co.uk
 * Description: A plugin that allows you to display code on your Website
 * Version: 1.0
 * Author: Paul Underwood
 * Author URI: http://www.paulund.co.uk
 * License: GPL2 

    Copyright 2012  Paul Underwood

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation. 

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
*/

/**
* Stop WordPress converting quotes to pretty quotes
*/
remove_filter('the_content', 'wptexturize');
remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');

/**
* Define the different language shortcodes
*/
$language = array("html", "css", "javascript", "php");

/**
* Create the different shortcodes
*/
foreach($language as $lang){
	add_shortcode( $lang, 'paulund_highlight_code' );	
}

/**
* Change the content of the shortcode to display code in the content
*
* @param $atts - Shortcode Attributes
* @param $content - Content inside the shortcode
*/
function paulund_highlight_code($atts, $content = null){
	
	$encode = false;
	
	if($content != strip_tags($content)){
		$encode = true;
	}
	
	if($encode){
	
		$remove_array = array("&lt;p&gt;", "&lt;/p&gt;", "&lt;br /&gt;", "&lt;br/&gt;");
		$content = str_replace($remove_array, "", $content);
		
		$content = str_replace("<", "&lt;", $content);
		$content = str_replace(">", "&gt;", $content);
	}
		
	$content = "<pre><code>" . trim($content) . "</code></pre>";
	
	return $content;
}

?>

Using The Shortcode

With the shortcodes active in WordPress we can now use them in the text editor.

All you have to do is decide which language you are going to paste into the text editor, if it is php then use the php shortcode. If you are using html then use the html shortcode tag.

Then all you have to do is write down the shortcode [ php ] then copy your code in the text editor then make sure you close your shortcode [ /php ].

When your HTML loads on the page these shortcodes will be changed to the pre tags.

Example of displaying code.

Styling The PRE Tags

When adding pre tags around the code it will not look great but this can easily be solved just by using CSS, all you have to do is add the following styles to the pre tags then all code snippets will look like this.

The below CSS is the styling I use on Paulund to style the code snippets. It will add different colour lines to the background of the pre tag and changes the line height so that each line of code will fit in each line of background rows.

Add this to your theme stylesheet to have the same style code snippets as seen here.

/***************************************************************************
 * 	Code
 ***************************************************************************/
pre {
	background: #eee;
background-image: -webkit-linear-gradient(#eee 50%,#e0e0e0 50%);
background-image: -moz-linear-gradient(#eee 50%,#e0e0e0 50%);
background-image: -ms-linear-gradient(#eee 50%,#e0e0e0 50%);
background-image: -o-linear-gradient(#eee 50%,#e0e0e0 50%);
background-image: linear-gradient(#eee 50%,#e0e0e0 50%);
background-position: 0 0;
background-repeat: repeat;
background-size: 4.5em 4.5em;
color: #555;
font-family: monospace, serif;
font-size: 16px;
line-height: 2.25em;
margin: 2em 2.25em;
overflow: auto;
padding: 0 2.25em;
width:85%;
}

To get a copy of the syntax highlighter used on Paulund it is available on github as a WordPress plugin.

Paulund Syntax Highlighter

Advertise here 50% Off

Comment