Adding Code To Wordpress Blogs And Comments

Wordpress is a pretty neat blogging platform, but it falls over quite spectacularly when trying to write code in posts. I write a lot of code for #! code and so I have understand what needs to be encoded to make code examples work.

For code example on #! code I use the code tag and I encode the following characters.

< into <
> into >
" into "
' into '

Note: You must be in HTML mode in your Wordpress editor or everything will be double encoded.

If these characters are left in then Wordpress will either keep them "as is" (ie, a br tag will cause a line break) or it will convert them into non standard characters. For example, typing a ' (single quote) is straightforward, but when your users come to copy and paste the code to try it for themselves they find that the characters Wordpress gives them cause the examples to fail. So every time you type a ' you have to encode it using '. The following example shows why typing a single quote will break your code examples.

echo ‘Hello World’;

The same thing applies to double quotes, as in the following example.

echo “Hello World”;

Wordpress will also try to guess what you are doing and add in tags where you don't want them. The effect of this is to break your code tags if you leave any space in them. Take the following example of a 4 line snippet of code, with a blank line between line 2 and line 4.

line 1
line 2

line 4

This is because Wordpress will see the blank line and try to add some tags in to make it look like it thought you wanted it. In order to stop this you need to put in a   (non breaking space) character on any blank lines that you have. The following example fixes the previous example.

line 1
line 2
 
line 4

 

Comments

Thanks for this article. I have been experimenting with wordpress and this issues was causing me problems. I have implemented the line break you suggest and it is now working a treat. Thanks a mill. Brian
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.