Created
March 25, 2016 02:57
-
-
Save QROkes/1806817316d0ef5d44d4 to your computer and use it in GitHub Desktop.
Embed Gist - WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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