Skip to content

Instantly share code, notes, and snippets.

@QROkes
Created March 25, 2016 02:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QROkes/1806817316d0ef5d44d4 to your computer and use it in GitHub Desktop.
Save QROkes/1806817316d0ef5d44d4 to your computer and use it in GitHub Desktop.
Embed Gist - WordPress
<?php
// Embed gist without JavaScript in WordPress
wp_embed_register_handler( 'gist', '/https?:\/\/gist\.github\.com\/([a-z0-9\/]+)([\?\#]file[=-].*)?/i', 'qr_embed_gist' );
function qr_embed_gist( $matches, $attr, $url, $rawattr ) {
if(empty($matches[1])){$matches[1]=null;}
if(empty($matches[2])){$matches[2]=null;} // Query single file
$file = wp_remote_get( esc_url_raw( 'https://gist.github.com/' . esc_attr($matches[1]) . '.json' ) );
if ( !is_wp_error($file) && 200 == $file['response']['code'] ) {
$giton = $file['body'];
$giton = json_decode($giton, true);
$embed = '<pre><code class="gist-embed">' . preg_replace( "/^\s+|\n|\r|\s+$/m", "", $giton["div"] ) . '</code></pre>';
wp_enqueue_style( 'gist', esc_url_raw( $giton["stylesheet"] ) );
}else{
$embed = 'Error: ' . $file['response']['code'] . ' - Invalid Gist URL';
}
return apply_filters( 'embed_gist', $embed, $matches, $attr, $url, $rawattr );
}
<?php
// Another way to Embed gist with <noscript> as fallback - WordPress
wp_embed_register_handler( 'gist', '/https?:\/\/gist\.github\.com\/([a-z0-9\/]+)([\?\#]file[=-].*)?/i', 'qr_embed_gist' );
function qr_embed_gist( $matches, $attr, $url, $rawattr ) {
if(empty($matches[1])){$matches[1]=null;}
if(empty($matches[2])){$matches[2]=null;} // Query single file
$urlx = esc_url_raw( 'https://gist.github.com/' . esc_attr($matches[1]) );
$file = wp_remote_get( $urlx . '.json' );
if ( !is_wp_error($file) && 200 == $file['response']['code'] ) {
$giton = $file['body'];
$giton = json_decode($giton, true);
$giton = strip_tags($giton["div"], '<a>');
$embed = '<script src="' . $urlx . '.js' . '"></script>';
$embed .= '<noscript><pre><code class="gist-embed">' . preg_replace( "/ |\s+$/m", "", $giton ) . '</code></pre></noscript>';
}else{
$embed = 'Error: ' . $file['response']['code'] . ' - Invalid Gist URL';
}
return apply_filters( 'embed_gist', $embed, $matches, $attr, $url, $rawattr );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment