Adding source code into WordPress blog posting

As demonstrated by another post of mine I finally figured out how to easily add source code into a WordPress blog posting. Searching on Google for this issue reveals large numbers of people facing the same problem. It makes you think that including source code in a WordPress 2.2.1 blog posting is the most difficult problem known to man.

Many of the problems seem to be caused by the visual editor in WordPress. It reformats code in ways that you are unlikely to want (such as trimming any whitespace), leaving your carefully constructed source code looking like a real mess.

The way to turn it off is to go to ‘Login -> Users -> Edit’ and then untick the ‘Use the visual editor when writing’. There seems to be no way to edit and then re-edit in-line source code when the visual editor is turned on, because when you re-edit your posting the visual editor reformats your code automatically – even if you don’t make any changes and switch straight to the code editor.

This problem is in part because if you have the visual editor enabled it becomes the default editor and re-formats any code that it loads. WordPress could easily fix this be allowing you to make the code editor the default editor so the visual editor only gets its hands on your posting if you give it permission. There is a discussion on the site about this here.

If you still want to use the visual editor then the workaround that I’ve seen mentioned is to create a second user account with the visual editor turned on. You then need to use the correct account depending on whether you will post source code or not and remember never to load your source code posts with the visual editor.

The next problem that I came across was that adding code within <pre></pre> tags causes the lines to be double spaced when using the default WordPress theme. I solved this by installing the CodeMarkup plugin which allows code samples to be displayed in a way which looks sensible to me. It automatically escapes all your code so that you can paste it directly in between <pre><code></code></pre> tags without having to use a tool tool to escape the special characters.

2 Comments on “Adding source code into WordPress blog posting”

  1. u can use a simple online app, TOHTML 

    here u can enter the source code , select the language and style and get html code ,that u can paste in the editor to get a formatted code, i have used it and it also highlights different syntax.. check this post for a demo.

Leave a Reply

Your email address will not be published. Required fields are marked *

Do NOT fill this !