WordPress: Style Gists with a shortcode

In Software Engineering, Snippet

Something I knew I wanted to do right off the bat after reviving this blog was include snippets of code. I also knew I wanted to use Github Gists to actually host the snippets (for its versioning benefits).

But I don’t particularly like Github Gist’s default embedded CSS. It’s not terrible, but it’s definitely something neutral that’s not going to offend anyone.

I was sure that someone had already made some plugin to embed and style gists… somewhere. But to my surprise, it didn’t seem like anyone had.

Styling an embedded gist didn’t seem too hard. Basically, I just had to look for a stylesheet I liked.

I found one at lonekorean/gist-syntax-themes. As it turns out, he not only put his stylesheets on rawgit, but had created an index.html for serving the repo as a GitHub Page as well! After some testing in the Chromium’s developer tools, it turns out that I could just add either

  • <link media="all" href="https://cdn.rawgit.com/lonekorean/gist-syntax-themes/848d6580/stylesheets/obsidian.css" rel="stylesheet"> or
  • <link media="all" href="https://lonekorean.github.io/gist-syntax-themes/stylesheets/obsidian.css" rel="stylesheet">

to my site’s header. (I couldn’t actually include the raw githubusercontent file, since that returns a response with Content-Type: text/plain, which triggers Cross-Origin Read Blocking in modern browsers).

I certainly didn’t want to use rawgit, since it’s shutting down, so using the sheet served from github.io seemed fine… but I wanted two more things:

  1. control over the CSS (in case it ever goes down, or if I want to modify it); and
  2. some way to only load this syntax highlighting CSS only on posts and pages that actually had gists I wanted to highlight.

The solution:

  1. Forking the styles repo on Github (I’m almost certainly going to be committing changes soon);
  2. Turning on the repo’s GitHub Pages setting (to avoid the CORBS issue); and
  3. Editing my theme’s functions.php file to
    1. register my preferred stylesheet as an enqueued script, and
    2. add a shortcode to enqueue the stylesheet

Now, whenever I want my embedded gists to be styled with that style, I just add my shortcode gist_obsidian to the end of my WordPress post.


Leave a Reply