With the code in this post, we can embed GitHub Gists on WordPress. Gist is an easy method to share code snippets or excerpts of data with others. Gist is owned by GitHub and used by millions of developers across the world.
Today, I’m excited to share this very handy code snippet which allow you to embed a GitHub gist on your blog, simply by pasting the gist url.
Add the function
Paste the following code into your functions.php file. Once done, simply paste the URL of a Github gist into a post or page.
The gist will be automatically embedded in your WordPress blog.
<?php
/**
*
* Example: https://gist.github.com/erossini/b91c67212c793a261629e287de4b411e
* Usage:
* [gist]erossini/b91c67212c793a261629e287de4b411e[/gist]
* [gist id="erossini/b91c67212c793a261629e287de4b411e" /]
*
* If a gist has multiple files you can select one
* [gist id="erossini/b91c67212c793a261629e287de4b411e" file="file-name" /]
*/
function add_gist_github_shortcode( $atts, $content = NULL ) {
extract( shortcode_atts( array(
'id' => '',
'file' => '',
), $atts ) );
if (function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) {
return sprintf('<amp-gist data-gistid="%s" %s layout="fixed-height" height="250"></amp-gist>',
$id ? $id : trim(esc_attr($content)),
$file ? 'data-file="' . esc_attr( $file ) . '"' : ''
);
} else {
return sprintf('<script src="https://gist.github.com/%s.js%s"></script>',
$id ? $id : trim(esc_attr($content)) ,
$file ? '?file=' . esc_attr( $file ) : ''
);
}
}
add_shortcode('gist', 'add_gist_github_shortcode');
?>
Use the shortcode
Two ways you could embed gist to WordPress blog post. Here is the best way to add Gist to WordPress using Shortcode?
This is the first method. Basically, you have to use the “tag” gist
and add the Gist ID.
[gist]erossini/1fad3e32630de777dd0d2183ae41e80f[/gist]
The second method is similar to the first one but, in this case, you specified the ID explicitly.
[gist id="erossini/1fad3e32630de777dd0d2183ae41e80f" /]