In this guide you will learn how to embed a GitHub Gist (code-snippet) into your website (WordPress and others).
Say you want a nicely formatted piece of code on your site, for example a WordPress site, but you don’t want to install any plugins or libraries.
Why not just embed a GitHub Gist like the one above? I’ll show you how!
What’s a GitHub Gist?
You probably already know GitHub, and if you don’t, well, you should! If you have a GitHub account (it’s free) you can use their service called GitHub Gist, which is a pastebin-style site to post any piece of text (usually code, with highlighting support) and, the feature we’re here for: Embedding it into your site.
Creating a Gist
First you’ll want to make sure you have a GitHub account, and are signed in, then you’ll want to go to https://gist.github.com/ and paste your piece of text or code. If you want code-highlighting, you’ll have to make sure to enter a file name with the correct extension, in our example it’s C, so we’ll name it something ending in
.c. Then choose whether it’s going to be a secret Gist or a public Gist, using the dropdown arrow (secret means only people with the link or embed will see it) and then press the button to create the Gist.
Embedding a Gist into your site (generic)
Once you pasted the Gist, it will show it to you, with the full URL in the address bar.
The URL in the address bar will look something like this:
There are a few neat things you can do with that URL:
- Share it (obviously)
/rawto the end to display the raw contents
To make your life easier, you can find a little text box at the top right of your Gist, saying “Embed” with a clipboard to the right of it. Click the clipboard to retrieve the script URL, already wrapped in script tags. You can use this copied snippet anywhere, where you can use HTML.
Now, on your site, either directly in the HTML or using some HTML embedding widget (if you’re using a CMS), paste it where you want it!
Read on for WordPress specific instructions…
Do as stated above, except to embed the copied snippet, you’ll want to go to your post or page you are editing (with the Gutenberg editor), go to the place just above where you want the code snippet, and hit enter to create a blank space/line. Click the plus icon to the right of the blank space and search for the block named “Custom HTML” and choose it.
Now paste the script snippet into it. You can now click preview if you like, to see what it looks like.
That’s all there is to it! At the top of this post, there’s an example Gist I embedded for you.
A Few Notes (Limitations and Security)