Posting short code snippets within a blog post can be an incredibly instructive and useful tool when used properly. Often, what I find on the web however is that this ability is compromised and ultimately lost in some thoughtlessly large block of code, that is garishly done up with syntax highlighting in distracting colors. To make better use of code snippets (say in Latex, C++, or HTML) I follow the following very simple rules:
- Each snippet is enclosed within
</code></pre>tags. The pre tag ensures that formatting is preserved while the code tag ensures that WordPress’ intrusive visual editor doesn’t interfere with the special characters within the snippet.
- Any special characters like the ampersand, less-than or greater-than symbols are escaped using the appropriate character sequences. If you don’t want to do this manually use this online service. If you use the visual editor in WordPress, any manual escaping seems unnecessary as text input into the editor is automatically escaped for you, even if copy-pasted. This was true at least in the cases I tried.
- Confusingly, there are two “visual editors” in WordPress. If you’re writing code do not use the editor that looks like this. It will gobble up all your escaped HTML. There’s a different visual editor made available through the WP Admin button the sidebar. Use that instead.
- Finally, keep code snippets to a minimum, and keep them short.
For an example take a look at one of my posts with code snippets.