Skip to content

Instantly share code, notes, and snippets.

@trepmal
Created November 19, 2012 20:58
Show Gist options
  • Save trepmal/4113841 to your computer and use it in GitHub Desktop.
Save trepmal/4113841 to your computer and use it in GitHub Desktop.
[WordPress] faux-Embed support for xkcd comics
<?php
/*
Plugin Name: xkcd oEmbed
Description: faux-Embed support for xkcd comics
*/
$xkcd_oembed = new xkcd_oEmbed();
class xkcd_oEmbed {
function __construct() {
wp_embed_register_handler( 'xkcd', '#http:\/\/(?:www.|)xkcd\.com\/(\d+)\/?#i', array( &$this, 'get_xkcd' ) );
}
function get_xkcd( $matches, $attr, $url, $rawattr ) {
$id = $matches[1];
$xkcd_cache = 'xkcd_cache_'. $id;
// delete_transient( $xkcd_cache );
if ( false === ( $img = get_transient( $xkcd_cache ) ) ) {
$get = wp_remote_get( $url );
$response = wp_remote_retrieve_response_code( $get );
if ( 404 == $response ) {
$img = make_clickable( "$url (comic not found)" );
set_transient( $xkcd_cache, $img, 60 * 60 ); // cache for an hour, try again later
return $img;
}
$body = wp_remote_retrieve_body( $get );
// cut off crud before the comic
$_body = explode( '<div id="comic">', $body );
$body = array_pop( $_body );
// cut off crud after the comic
$_body = explode( '</div>', $body );
$img = array_shift( $_body );
$img .= "<a href='$url'>xkcd #{$id}</a>";
set_transient( $xkcd_cache, $img, 60 * 60 * 24 * 30 * 12 ); // cache for a while. expiry value of 0 is auto-loaded, which we don't need/want
}
return "<p>{$img}</p>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment