Update: With the new theme on this website, I have not actually styled this sucker and all of the formatting I did prior is now lost. I may bag this plugin for another. If anyone has any suggestions, drop me a line.
Displaying code snippets in WordPress can be a chore. Fortunately there are several plugins to choose from that will help you maintain the original formatting.
My plugin of choice right now is Scott Reilly’s Preserve Code Formatting. Scott’s plugin prevents modification by WordPress and other plugins while retaining original whitespace and characters.
I looked at other plugins that included syntax highlighting, but quickly dismissed them. Syntax highlighting produces a ton of inline style spans wrapping the code fragments, and frankly, my choice of styling choices may not agree with your choices.
Now I can just paste code into <code>, <pre>, and/or other tags I can additionally specify and this plugin will:
- Prevent WordPress from HTML-encoding text (i.e. single- and double-quotes will not become curly;
---will not become en dash and em dash, respectively;
...will not become a horizontal ellipsis, etc)
- Prevent most other plugins from modifying preserved code
- Optionally preserve whitespace (in a variety of methods)
- Optionally preserve code added in comments
One caveat with the plugin is that you turn off the Visual Editor in your WordPress settings. No biggy, I do this anyway.
Another quirk to the plugin is that it appears that the code block seems to get double wrapped with the <pre> tag. Why it does this, I do not know. But I took advantage of the quirk in my style sheet to apply a border effect.
/* additional <pre> element added to Html output *//* start of my post's code snippet */ ... my code snippet sample here
The option to preserve code in comments (on by default) was left on. This will come in handy for any commenters who wish to leave sample code snippets if they wish. So give it a try, that will be kewl to do.
Leave a comment if you are using this plugin and tell me about it. Or another plugin that you are using. Will be interested in seeing some samples in action.