Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active September 28, 2022 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sabrina-zeidan/d288e30f36dfc11e7e631429671e2176 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/d288e30f36dfc11e7e631429671e2176 to your computer and use it in GitHub Desktop.
Paste gist.github.com URL in Gutenberg -> get the embed [WordPress]
//Important: When adding a gist link in Editor you MUST choose - convert to link, not Embed!
//Embed Gists to be displayed in Gutenberg without plugin, works on new and existing ones
add_filter( 'the_content', 'sz_embed_gists_in_gutenberg' );
function sz_embed_gists_in_gutenberg( $content ) {
if(empty($content)) return;
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$dom->loadHTML($content);
$paragraphs = $dom->getElementsByTagName('p');
$domElemsToTarget = array();
foreach ( $paragraphs as $paragraph ) {
$paragraph_content = $paragraph->nodeValue;
if (strpos($paragraph_content, "gist.github.com") !== false) {
$domElemsToTarget[] = $paragraph;
}
}
foreach( $domElemsToTarget as $domElement ){
//in case it's a link to a specific file inside the gist:
$p_content = $domElement->nodeValue;
$url_string = explode('#',$p_content);
//create link
$link = $dom->createElement('script');
$specific_file_string = (!empty($url_string[1])) ? "?".preg_replace(['/^file-/','/-php$/'],['file=','.php'],$url_string[1]) : '';
$link->setAttribute('src', $url_string[0].".js".$specific_file_string);
//wrap it in <p> (for some reason, <script> that goes just after the <h> tag without wrapper gets missed out)
$p_new = $dom->createElement('p');
$p_new->setAttribute("class", "gist-embed-php");
$p_new->appendChild($link); //nest it
$domElement->replaceWith($p_new);
/** For PHP < 8
//remove initial contents of the paragraph
while ($domElement->hasChildNodes()) {
$domElement->removeChild($domElement->firstChild);
}
//append the new one
$domElement->appendChild($p_new);
**/
}
$content= $dom->saveHtml();
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment