Putting Readable Code in a WordPress Post

Writing about PHP or HTML code in WordPress posts or pages often requires that some actual code is shown on the screen for explanation. If special steps aren’t taken to illustrate the code as text, the result is often not what was intended to be seen because the WordPress engine will interpret the code as actual code, not text about code.

If all you want to do is highlight some text that includes code-related words like filenames, function names or plugin names, use <code></code> around those phrases in your text. Using <code></code> turns text into a monospaced font so that it appears differently in your posts than “normal” text. However, using <code></code> around an HTML tag doesn’t do anything except change the presentation of the tag, so the opening and closing angle brackets are interpreted to enclose an actual HTML tag. The result will be a mess and definitely not what you were hoping to see.

To make WordPress show code in a post without interpreting it, you have to do ONE of three things:

  1. Use special character codes to replace angle brackets of tags.
  2. Use the HTML tag <pre></pre> around the code.
  3. Use a plugin to highlight the code syntax.

1. Special Character Codes

Angle brackets, < or >, are what WordPress uses to identify code, whether it’s HTML, inline styles of CSS, or PHP. Content inside angle brackets is interpreted as code by virtue of placement inside the brackets. Instead of interpreting this code we want WordPress to show the code to the site visitors and we can use special character codes to do that.

Character codes are special sequences of letters or digits that are used to represent textual characters. Every character that we see on the screen, including uppercase letters, lowercase letters, numbers, and symbols like <, >, #, $, %, ^, & or *, can be represented by character codes, sometimes called character entities.

Using character codes in posts looks a little strange in the editing panel, but when a browser comes across these codes they are interpreted and their textual equivalent is shown on the screen.

ASCII (American Standard Code for Information Interchange) character codes were developed to represent text in electronic devices and they follow a specific format. The format is that each character entity starts with an ampersand and ends with a semi-colon. The codes are a couple to a few letters or numbers. Numbered character codes always have a hash symbol right after the opening ampersand. Some entities can be represented by either numbered or named codes.

Examples of special character codes:

Character name Character symbol Character ASCII Code
left angle bracket < &lt;
right angle bracket > &gt;
ampersand & &amp;
dollar sign $ &#36;
long dash &mdash;
short dash &ndash;
double quotes " &quot;
at sign @ &#64;

If you need to find a code for language sets other than English, try the unicode site for all the code charts you’ll ever need. There, you can find numeric codes for fun game pieces, like chess, mahjong or checkers, horoscope symbols, smiley faces, weather symbols, music notes, and much more.

Take caution: Just because you can enter a special code to represent a symbol, that doesn’t mean your computer will let you see it. Many operating systems will not have the proper fonts installed to make use of all of these codes, especially if they represent symbols that aren’t on your keyboard. Stick to the ASCII codes as many of the unicodes won’t be seen by your site visitors.

2. HTML tag: <pre>

Perhaps you’d like to show a block of HTML code on your post and have it shown as text. To make sure that your block of code is not interpreted as actual code, wrap it with <pre></pre> tags. The <pre> tag will change the appearance of the code into a monospace font, just like <code> does, but the difference is that <pre> also illustrates the code exactly as it was typed. All text, characters, spaces and line feeds will be reproduced exactly how they were entered. No code will be run when it’s protected inside the opening <pre> and closing </pre> tags.

3. Syntax Highlighter Plugins

A final way to illustrate code in a WordPress post or page is to use a plugin to highlight the code. Several plugins are available for syntax highlighting purposes.

One that I have been using lately is called Crayon Syntax Highlighter. It’s a great plugin that will colorize or highlight code that you wrap with shortcodes. There are lots of options if you want fine control over the color scheme. Themes come with the plugin so you have several choices for making your code look good.

There are two modes where you can highlight code differently using shortcodes, [crayon][/crayon] and [plain][/plain]. Use [plain] shortcodes when the colorized crayon is overkill or when you just want to show a small section of code. Crayon Syntax Highlighter supports a wide range of languages, including HTML, CSS, PHP and JavaScript, for starters.

The colorful [crayon] shortcode is controlled by options where you can pick the colors that you want for representing different sections or purposes in your code. Inline crayons are supported so you could put a line of code within a line of text and the code would be colorized.

Some other popular code-highlighting plugins include SyntaxHighlighter Evolved, WP-Syntax, and CodeColorer. I don’t have any personal experience with these plugins, but they are listed high in popularity at the WordPress Plugin Directory.

Need to Execute Code in a Post?

If what you’re really after is to put executable code in a post or WordPress Page, check out this post on executing PHP in WordPress blogs.

Using PHP Inside Content of WordPress Blogs

Using PHP inside of content on WordPress sites may not produce the expected results. As WordPress is built in PHP, you might think you could just start typing PHP code inside a post to pull some information from a database. Sorry to say, but it doesn’t work that way.

WordPress takes your blog content and runs it through some backend shenanigans to create the output that you see on the screen. WP expects to find other content in posts, like text and images, not code.

To run PHP code inside a blog post or Page, you’ll have to work a little differently than simply filling up the space in the text editor.

There are two ways (at least) of using PHP inside WP blogs to produce the desired output. The first way is to set up a WP template page that points to a pre-written PHP page that is identified in a Page. The second way is to use a plugin that facilitates PHP code execution inside content areas in WordPress. Both ways have their advantages and disadvantages.

Using WP Template Pages to Execute PHP Code

A template page is used to identify a pre-written PHP page. By saying “a pre-written PHP page” I mean a .php file that you’ve already written and which has been executed successfully by a server. A template file has at the top of it a PHP comment which identifies the template name followed by an include statement that identifies the .php file. WP template files must follow this format to be properly identified by the WordPress engine as a template file.

<?php
/*
Template Name: soccer-roster
*/
include (TEMPLATEPATH . ‘/soccer-roster.php’);
?>

The above snippet  is a complete template file which indicates the name of the template as “soccer-roster” and the path to the associated PHP file, soccer-roster.php. The template file is best saved with “template” in the file name. It must be located in the site’s theme folder.

After creating the template file and .php file, upload both to the theme folder. Create a blank Page. Do not put anything where you would normally write the content, but go ahead and give it a meaningful title. On the Add New Page page, look for the “Page Attributes” widget. Click the down-arrow to expand the list of templates and select your template. Using the example above, you would select the “soccer-roster” template. If the template is not stored in the theme folder, it will not appear in this drop-down list. Save the page and preview it. The PHP code, from soccer-roster.php, should be executed just as you would expect.

PROs

  • No interference from WP, code interpreted as stand-alone PHP.
  • Page renders as expected.

CONs

  • Can only be used with Pages, not posts or text widgets.
  • May have to wrestle with adapting PHP output into style of site.
  • CAUTION: Use a child-theme to safely save site-specific template files.

If your site relies heavily on plugins, using template pages may be the best method, see below. If it’s not a big deal to style the PHP output pages like the rest of your site, creating WP Pages that use templates is a breeze. If you need to put code in a post or text widget, keep reading.

Using WP Plugins to Execute PHP Code

Modifying WordPress themes is not for everyone, so using a plugin to execute PHP code may be the easier option. There are more than a handful of plugins available for the task. I chose to use Exec-PHP plugin for WordPress. It is a very well documented plugin. Thank you, Sören.

Download, unpack, upload and activate the plugin in the usual fashion. Verify these settings to make the plugin do its magic:

  • Disable tag balancing by unchecking ‘WordPress should correct invalidly nested XHTML automatically’ in the Settings/Write menu.
  • Disable the WYSIWYG editor (visual editor) in the user’s settings through the Users/Your Profile menu.
  • Assign the ‘unfiltered_html’ capability to the user, if user is not the administrator. Can use role manager plugin to assign this capability to other users.
  • Assign the ‘exec_php’ capability to the user, if user is not the administrator. Can use role manager plugin to assign this capability to other users.

Once I disabled the visual editor, my site was ready to go.

PROs

  • Easy, just change a couple of settings in blog admin. Plugin gives highly visible warning on Add New Post or Add New Page pages if the settings are not correct.
  • PHP code can be written in the normal fashion using the <?php ?> tags. It does not need to be marked up in any special way as it might with other plugins.
  • PHP can be used in text widgets and posts, as well as Pages.

CONs

  • Can’t use plugins that embellish or rely on the WYSIWYG editor.

Didn’t try any other PHP-execution plugins because Exec-PHP worked as soon as the visual editor was disabled.

As mentioned either method will get you there, it’s just a matter of style. If you need the visual editor to create your posts, use the template method. If you want to put PHP code in posts and text widgets, use the plugin method. Good luck!

Twenty Ten Child Theme Mods

Creating WordPress child themes is a slick way to make your own theme. All it takes are a few easy steps. Here’s an example using the standard Twenty Ten theme as the parent theme:

  • modify the child-stylesheet to make things look how you want
  • create child-directory for new child theme
  • add template files to child-directory, if you wish
  • upload child-directory to /wp-content/themes/
  • activate new child theme

The child-stylesheet must be saved with the name “style.css” in the child-directory. The child-stylesheet header (which has to be at the top of the sheet) must contain a few lines that identify its parent theme, like so:

/*
Theme Name:     Twenty Ten Child
Description:    Child theme for the Twenty Ten theme
Author:         Your name here
Template:       twentyten
Version:        0.1.0
*/

@import url("../twentyten/style.css");

{put new style rules here}

You can add a line for the Theme URI: and Author URI:, if you like. Only the Theme Name: and Template: lines are required, the others are optional.

The @import rule indicates the directory of the parent theme and the location of the stylesheet. All you have to do is put in the new css rules below the import line.

That’s it!

If modifying the stylesheet doesn’t quite get all the changes you want, realize that you can add any template file to the child-directory and that will over-ride the parent file with the same name. For example, say you want to stick in a block for an advertisement right under the header image. Copy header.php and add a new <div> at the bottom of the page just below <div id=”main”> and stick the ad code in this division. Upload this new header.php into the child-directory and it will replace the one from the parent template.

Activate your new child theme and see how it looks!

Comment, comment, comment…but which comment code goes where?

Commented code is worth its weight in gold when it comes time to decipher it. Unfortunately, the codes for commenting in xhtml, css and php are not all the same. So, for reference sake here are the comment codes you’ll need and where to use them.

Where xxx is your comment, for

  • xhtml (html) and php (outside php code) use <!-- xxx -->
  • css use /* xxx */
  • php (inside php code or between <?php and ?>) use // xxx
  • multi-line comments inside php use /* xxx */

Comments are very helpful in troubleshooting style changes. When creating your designs take a few seconds to jot down a comment here and there.

Great uses of comments include labeling the starting and ending location of id- or class-identified divs, putting temporary holds on features that may or may not be needed in the final design — often called commenting out code, sectioning long stylesheets into more easily readable forms, and specifying the author or location of the code.