Adding Code To Wordpress Blogs And Comments

5th February 2009

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.

  1. < into <
  2. > into >
  3. " into "
  4. ' 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.

  1. line 1
  2. line 2
  3.  
  4. 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.

  1. line 1
  2. line 2
  3.  
  4. line 4

 

Comments

Permalink
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

Anonymous (Mon, 05/10/2010 - 15:07)

Add new comment

The content of this field is kept private and will not be shown publicly.