• Posted: 2012-02-07
  • Author: Idered
  • Tags:

Github Gist Shortcode

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
<?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);
?>

Instructions:

This code will detect links to Github Gist in posts and replace them with shortcodes then shortcodes will be replaced with embeded gist. Just add the code to your functions.php.

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]

This 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 file name in gist is uppercased. But this one will work corectly:

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


Share this snippet

If you like this snippet, share it with friends!