Using Gist to Embed Easily Copied Code Snippets

Editor’s note: I am in the process of finishing an article that uses this feature so I thought to share it first!

I write a lot of articles that include sample code as an illustration. In WordPress, I have tried a number of plugins to do syntax highlighting which is good for illustrative purposes. If you reading that article and then want to include it in some work that you are doing, copying it and pasting it should be easy, right? And I mean easy, not worrying about spacing, background code that might interfere or have to be removed, pretty line numbers that just won’t go away, etc. If you are like me, you possibly use GitHub, BitBucket, or other online code management system. Why not just display the code direct from those same repositories? The other day, I was reading a post that did just that, using Gist. The folks from GitHub describe it as a simple way to share snippets and pastes with others. Best part is that when I find an oops in the code, no need to revise the post since the clip is pulled from a Git repository! Change the code and it is corrected when the post is displayed.

So, let’s do an example! This assumes that you have an account on GitHub. Not there yet? Simply, go here, sign up, and confirm your email address. You can create and store unlimited public repositories. Private ones are not free. (Note to self: write up how I use GitHub and BitBucket.) After you sign in, go to Gist. You add a description, give it a name, create your snippet of code, save it, and share it! The one to the right is the one that I created for this article, an HTML5 skeleton I found at Snipplr.

You can view this snippet here on Gist, but what makes it wonderful is that all you do is add a WP shortcode and it appears right here, inline with your article! The shortcode is simply:

1

[gist]123456[/gist]

where 123456 is the final part of the Gist’s URL. This is fully documented at WordPress. Here is that snippet of code:

You can click the name of the snippet which will take you to the repository on GitHub. You can then clone that Gist into your own GitHub account. You can also comment on it right there, as well as all the other GitHub functionality. By clicking view raw, you can display the actual code in your browser without formatting that you can copy/paste or save.

This is just another way to not only keep your code snippets organized, but also share them easily!