404 Tech Support

Use Github Gists to embed code on your WordPress site

Occasionally, I like to share code snippets here on 404 Tech Support. I have tried various methods and have not really been satisfied with them. Formatting the code as pre-formatted does not let it stand out enough and still leaves it at the mercy of WordPress formatting. Various WordPress plugins offer Syntax Highlighting capabilities but it can mean an extra CSS and JavaScript file with every page load. Adding the code can also be cumbersome and if you want to change plugins, the old code is left surrounded by non-functional WordPress shortcodes.

Looking for a better approach, I am liking the options allowed by Github Gists. It allows you to create a page of your code (including multiple files), track revisions, and share the Gist multiple ways. You can embed the code by pasting in a script src but that can get lost in the WordPress visual editor. You can also share a URL to the Gist. With the help of a WordPress plugin called oEmbed Gist, WordPress can automatically turn that URL into embedded content, just like it does for YouTube videos.

One reason that this is a better solution than the Syntax Highlighter plugins is that if you deactivate the oEmbed Gist plugin, your content now has a URL pointing to the Gist on GitHub instead of mangled code. This also means that there are no extra requests on your other pages.

With the oEmbed Gist plugin activated, as soon as you paste a gist.github.com URL, it will render it as the embedded code so you can preview the final contents.

For an example, I created a new gist on GitHub using a snippet of PowerShell code. I named the file and saved it. Then, I copied the URL and pasted it below. You can embed specific revisions or single files of an multi-file Gist.

https://gist.github.com/jhamilton09/cbf3b5ef6279b31fc5d0

The code is clean and means that you can copy+paste it easily for your own use or clone it from GitHub. The quotes and spacing will not get messed up by WordPress or the browser’s rendering. I look forward to using this in future posts. It should be less tedious and frustrating than previous plugins that I have tried.