Displaying code snippets are essential for programming blogs and other related blogs. But its a little tricky thing, because WordPress parses each and every character and symbols in the post and removes the symbols like < and > if cannot recognize its use. And if finds the use of an HTML tag within the post, it will use the tag like it is HTML.

Inserting Code Inside WordPress Post

In simple words, we need to differentiate between the code to be executed and the code which is to be only displayed.

Putting code in your post that “looks” like code, but “doesn’t behave” like code, is a frequent challenge for bloggers. – WordPress Codex

To differentiate we need to use equivalent html character entities instead of the symbols in the code snippet. For eg. replacing < and > with &lt; and &gt;.

Here is a list of the most common HTML character entities:

< = &lt;
> = &gt;
/ = &#47;
] = &#93;
[ = &#91;
" = &#34;
' = &#39;

If every symbol in the code snipped will be replaced to its proper html character entity the code will not be executed and will be displayed with the post content. There are also some other things to be taken care of while inserting code snipped in WordPress post, which are mentioned below.

The points to consider while inserting Code Snippets into WordPress Post

If Code Snippet is to be Executed

1. Paste the code snippet in html editor. WordPress will execute it, if recognizes the codes. And the code will not be displayed in the post content.

If the Code Snippet is to be Displayed inside the Post Content

1. Paste the code snippet in visual editor. WordPress will convert symbols to the equivalent html character entities, for eg. < and > to &lt; and &gt;.

2. Wrap the code inside <pre><code> … </code></pre>



code snippet…


Why <pre> and <code> Tags are used

code: turns text into monospaced type and distinguishes text that is computer code from normal language.

pre: exactly reproduce whatever is inside of the <pre> tag, every space, line break, every bit of code is exactly reproduced.

Styling the Code Snippet

Paste this css to style.css file of your WordPress theme. This will give a different look to the code snippet.

code { border-left: 5px #DDD solid; background: #F5F5F5; padding: 5px 0 2px 10px; margin: 0 0 10px 20px; font: 12px Monaco, "Lucida Console", "Courier New", "Courier", monospace; display: block; overflow: auto; }

Many plugins are available for the same task but I think it is a simple task and can be done without using any plugin.

If you experience any problem feel free to share with us in comments.