Skip to content

Instantly share code, notes, and snippets.

@afragen
Last active August 5, 2022 19:56
Embed
What would you like to do?
WordPress plugin to embed gists or gist files.
<?php
/**
* Gist oEmbed.
*
* @package Fragen\Gist_OEmbed
*
* Plugin Name: Gist oEmbed
* Plugin URI: https://gist.github.com/afragen/36ab01da116aadd27a3f4d85cce90390
* Description: oEmbed Gist or files within Gists.
* Version: 0.6.2
* Author: Andy Fragen, Colin Stewart
* License: MIT
* Requires at least: 5.9
* Requires PHP: 7.1
* GitHub Plugin URI: https://github.com/afragen/oembed-gist-files
* Primary Branch: main
*/
namespace Fragen;
/**
* Exit if called directly.
*/
if ( ! defined( 'WPINC' ) ) {
die;
}
wp_embed_register_handler( 'gist', '#^https?://gist.github.com/.*#i', [ new Gist_OEmbed(), 'gist_result' ] );
/**
* Class Gist_OEmbed.
*/
class Gist_OEmbed {
/**
* Render Gist for embed.
*
* @param array $url Gist URL.
*
* @return string
*/
public function gist_result( $url ) {
$url = $url[0];
$fragment = '';
$parsed = explode( '#', $url );
// Parse elements of URL for specific file within Gist.
if ( isset( $parsed[1] ) ) {
$url = $parsed[0];
$fragment = str_replace( 'file-', '', $parsed[1] );
$file_arr = explode( '-', $fragment );
$ext = array_pop( $file_arr );
$fragment = implode( '-', $file_arr ) . '.' . $ext;
$fragment = '?file=' . $fragment;
}
if ( ! str_ends_with( strtolower( $url ), '.js' ) ) {
$url .= '.js';
}
$url = ! empty( $fragment ) ? $url . $fragment : $url;
// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
return '<script src="' . esc_url( $url ) . '"></script>';
}
}
@jdevalk
Copy link

jdevalk commented Aug 1, 2022

Might I suggest a defer be added to this script tag here?

@afragen
Copy link
Author

afragen commented Aug 2, 2022

Hmm, I think I added it correctly.

return '<script src="' . esc_url( $url ) . '" defer></script>';

which returns

<script src="https://gist.github.com/afragen/e1aa3ffccf1a73618ee6e756bd95d297.js" defer></script>

Unfortunately, it no longer renders. Do I have this set up correctly?

@afragen
Copy link
Author

afragen commented Aug 3, 2022

Apparently this is a thing. wp-media/wp-rocket#1117

@jdevalk
Copy link

jdevalk commented Aug 3, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment