Highlighting source code on wordpress.com hosted sites

I’ve never hosted a blog on wordpress.com. While I’m enjoying the “freeness” of the site, I’m struggling with not being able to edit themes and install plugins.

At first I was worried that without plugins I wouldn’t be able to highlight source code. After some digging, I was fortunately able to find a couple of different ways to do code highlighting.

Use the WordPress built-in shortcode

The simplest way to highlight source code on a hosted WordPress site is to use the built-in sourcecode shortcode.

The following markup

[sourcecode language="html"]
<div>
    <h1>Hello, World!</h1>
</div>
[/sourcecode]

produces

<div>
    <h1>Hello, World!</h1>
</div>

There are a lot of great parameters that can be used to configure the code box features which include highlighting specific lines, controlling the line wrapping, and collapsing the code box on page load, to name a few.

Embedding GitHub gists

Source code highlighting is great, but sometimes it’s nice to have revision history so that readers can see bug corrections.  Gists are great throw-away Git repositories that can be used for snippets and pastes.  Gists also have the added benefit of being portable.  If you ever outgrow wordpress.com, you can take your code snippets with you.

Gists are normally embedded on a site using javascript.  I was excited to try it out, but was disappointed to discover that wordpress.com does not allow inline javascript to be added to posts.  After searching a bit, I discovered that a gist shortcode was added specifically for embedding gist source code in WordPress posts.

Embedding all gist files

A gist can easily be embedded in a post using

[gist https://gist.github.com/4554439 /]

Which produces

<!DOCTYPE html>
<html>
<head>
<title>Example HTML Code</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="obnoxious">Blam!</div>
</body>
</html>
view raw index.html hosted with ❤ by GitHub
.obnoxious {
font-weight: bold;
font-size: 42px;
color: #FF0000;
}
view raw styles.css hosted with ❤ by GitHub

Embedding individual files from a gist

A neat trick that isn’t listed on the WordPress gist support site is the ability to embed individual files from a gist.

If I only wanted to show index.html, I would use

[gist file="index.html"]https://gist.github.com/4554439[/gist]
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Code</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="obnoxious">Blam!</div>
</body>
</html>
view raw index.html hosted with ❤ by GitHub
Tagged ,

One thought on “Highlighting source code on wordpress.com hosted sites

  1. health says:

    Hello, i believe that i noticed you visited my blog so i got here to return the favor?.I am trying to find issues to
    enhance my web site!I guess its good enough to use
    a few of your ideas!!

Leave a comment