Skip to content

Instantly share code, notes, and snippets.

@bcole808
Created May 7, 2015 21:37
Show Gist options
  • Save bcole808/9ad78c3bee57de8b7f14 to your computer and use it in GitHub Desktop.
Save bcole808/9ad78c3bee57de8b7f14 to your computer and use it in GitHub Desktop.
WordPress Embedly Integration
<?php
/***************************
* Custom implementation of the Embedly service
****************************/
class Embedly_WordPress_Integration {
private $cache_ttl = WEEK_IN_SECONDS;
private $embedly_uri = 'http://api.embed.ly/1/oembed';
public function __construct() {
// Register additional handlers
wp_embed_register_handler('amazon', '#https?:\/\/([a-z0-9]+[.])?amazon.com\/(.*)#i', array($this, 'embedly_handler'), 100);
}
//
// Handle an embed request of any kind
public function embedly_handler($matches, $attr, $url, $rawattr) {
// Check for cached data
if (false !== $data = $this->cache_get($url)) {
return $data;
}
// Get new data
if (false !== $data = $this->fetch_new_data($url)) {
$html = $data['html'];
$this->cache_set($url, $html);
return $html;
}
// Failure
return false;
}
private function fetch_new_data($url) {
// Try to fetch new data
$args = array(
'timeout' => 3,
'blocking' => true,
'headers' => array('Content-type' => 'application/json'),
'sslverify' => true
);
$params = array('url' => $url);
if (false) $params['key'] = 'KEY';
$request_uri = $this->embedly_uri . '?' . http_build_query($params, '', '&');
$response = wp_remote_get($request_uri, $args);
return json_decode(wp_remote_retrieve_body($response), true);
}
//
// Retrieve cached response if available
private function cache_get($url) {
$key = $this->hash($url);
return is_multisite() ? get_site_transient($key) : get_transient($key);
}
//
// Store cached response
private function cache_set($url, $result) {
$key = $this->hash($url);
return is_multisite() ? set_site_transient($key, $result, $this->cache_ttl) : set_transient($key, $result, $this->cache_ttl);
}
private function hash($string) {
return 'embedlyx'.md5($string);
}
}
new Embedly_WordPress_Integration();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment