How to include code fragments in a WordPress blog post

I’ve had to re-learn how to put fragments of code in a WordPress blog a couple of times (thanks to a longish break without posting), so I’m adding some notes on how to do it here, leaving no excuse for badly formatted code next time..

Problem:  You want to paste some code in your blog post, and when you publish the post, WordPress has changed the double quotes into different begin and end quote characters, and the spacing is all different. If you edit the HTML directly and paste it there, you have to escape all special characters like ‘<‘ and ‘>’, and the spacing is still messed up.

How to fix this has been well documented, for example: Writing code in your posts, but I’m looking for something simpler than editing the template header file.

You can use the <code></code> tag, but it doesn’t help with the spacing or special characters.

You can use the <pre></pre> tag to help with formatting but it doesn’t look much like you’d expect code to look (font, contrast with rest of post).

The easiest solution I’ve found is to combine some simple methods:

  1. Paste the code in HTML (not Visual) mode.
  2. Combine <code> and <pre> blocks so it looks like this:
    <code><pre>
    Your code…
    </pre></code>
  3. Escape special characters, e.g. “<” becomes “&lt;” and “>” becomes “&gt;”.

For example code like this:

<code><pre>
// &lt;your comment here&gt;
private void deleteButton_Click(object sender, RoutedEventArgs e)
{
string deleteURL = urlBox.Text;
string response = doDELETE(deleteURL, GetAccessToken());
outputBox.Text = response;
}
</pre></code>

Will look like this:

// <your comment here>
private void deleteButton_Click(object sender, RoutedEventArgs e)
{
    string deleteURL = urlBox.Text;
    string response = doDELETE(deleteURL, GetAccessToken());
    outputBox.Text = response;
}

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

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