X

Github Gist Shortcode

Snippets by IsItWP

If you want to detect links to Github Gist in posts and replace them with shortcodes, then shortcodes will be replaced with embeded gist.

Instructions: Add the following code to the functions.php of your WordPress theme.


<?php
// [gist id="ID" file="FILE"]
function gist_shortcode($atts) {
  return sprintf(
    '<script src="https://gist.github.com/%s.js%s"></script>', 
    $atts['id'], 
    $atts['file'] ? '?file=' . $atts['file'] : ''
  );
} add_shortcode('gist','gist_shortcode');

// Remove this function if you don't want autoreplace gist links to shortcodes
function gist_shortcode_filter($content) {
  return preg_replace('/https://gist.github.com/([d]+)[.js?]*[#]*file[=|_]+([w.]+)(?![^<]*</a>)/i', '[gist id="${1}" file="${2}"]', $content );
} add_filter( 'the_content', 'gist_shortcode_filter', 9);
?>

Formats:

https://gist.github.com/1147076
https://gist.github.com/1147076#file_annotated.js
https://gist.github.com/1147076.js?file=annotated.js
[gist id=1147076]
[gist id=1147076 file=annotated.js]

It works perfectly in most cases, but there is one (or more?) case when it doesn’t work as it should:
https://gist.github.com/1147076#file_license.txt

If we add this URL to our post, it will display all files from this gist. It’s because the filename in gist is upper-cased. This one will work correctly:

https://gist.github.com/1147076.js?file=LICENSE.txt

You may also enjoy checking if shortcode already exists.

[code]', $atts['id'], $atts['file'] ? '?file=' . $atts['file'] : '' ); } add_shortcode('gist','gist_shortcode'); // Remove this function if you don't want autoreplace gist links to shortcodes function gist_shortcode_filter($content) { return preg_replace('/https://gist.github.com/([d]+)[.js?]*[#]*file[=|_]+([w.]+)(?![^<]*)/i', '[gist id="${1}" file="${2}"]', $content ); } add_filter( 'the_content', 'gist_shortcode_filter', 9); ?>[/code]

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!