Uncategorized

Posting Source Code in WordPress

Perhaps it is just me, or perhaps I need to learn to use google better, but it took me quite a while to figure out how to post source code in wordpress properly. Here is a walk through for anyone else who is battling this:

Use the {code} … {/code} tags. These tags tell wordpress to ignore anything inside them when it is rendering the webpage. (IMPORTANT: replace the ‘{}’ brackets with ‘[]’, I have used ‘{}’ here simply so that you can see them! If you enclose your code in these tags, you will get:

#include <stdio.h>

int main (void) {

printf ("Hello, world!");

return 0;
}

set your language of choice with {code language=”python”}. You can set your language and this will then provide syntax highlighting appropriate for that language. Pretty neat. The code snippet above does not have a language set, but we can set it to “c”:

#include <stdio.h>

int main (void) {

printf ("Hello, world!");

return 0;
}

Now this all seems quite simple, what really tripped me up is being able to indent your code. Notice how all the code is left-aligned? It hasn’t kept any indentation:( Turns out, that you can’t do this in the visual editor, you need to switch to the text mode. Go up to the toolbar at the top of your post, and at the far right hand side (“Add Media”, “Add Poll”, “Add Contact Form”….”Visual”, “Text”) you will be able to switch this over. Now when you type in your code, all the indentation will be maintained:

#include <stdio.h>

int main (void) {

    printf ("Hello, world!");

    return 0;
}

So there we go. There are a whole lot of cool plugins for wordpress that will do this for you too. But to me, this seems like a quick and easy way to do things.

Advertisements

One thought on “Posting Source Code in WordPress

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s