Displaying source code in Wordpress post
After spending 5 mins setting up my Wordpress installation and then half the evening figuring out how to get syntax highlighting working (duh), I thought this post might come in handy for other newcomers to Wordpress.
So the first post I found when searching Google was one entitled “How do I post source code“. After seeing that they utilised syntaxhighlighter Google Code project by Alex Gorbatchev I assumed it was a built in feature…so like a fool I tried in vain to enter some test PHP code within these tags, like so but nothing worked…uuggh
[sourcecode language='php']echo ‘Why are you not working??’;[/sourcecode]
Little did I know that this was a feature included in Wordpress accounts installed at wordpress.com…as I soon found out from this test http://carltondickson.wordpress.com/2008/03/02/testing-source-code/
So anyway I found that the thing to do is install the http://wordpress.org/extend/plugins/google-syntax-highlighter/, the installation instructions are found here. Usage is a little different to what would be done on wordpress.com. Instead of using sourcecode tags you use the pre tag which contains a name attribute and then a class attribute specifying the language of the code you are displaying.
So to display the code I have below I used the following:
<pre name="code" class="php">
echo 'Got you working now!';
echo get_include_path();
exit('Exiting script now');
</pre>
echo 'Got you working now!';
echo get_include_path();
exit('Exiting script now');
Read the usage page for more info on this quality plugin.
Oh by the way, if you get a funny margin in your code output (below) it’s probably because of your theme, I was using “WordPress Default” and was getting code output that had spaces inbetween the lines which made it look pretty poo compared to examples I had seen. A quick check in Firebug and found it was because of a margin property and some other border related style…
html > body .entry li {
margin:7px 0pt 8px 10px;
}
[...] though, I just couldn’t get it working. After some searching I found out from this post (thanks to the unknown author!) that I needed to install the Google Syntax Highlighter for [...]