Created
April 23, 2014 09:47
-
-
Save gabrielmerovingi/11209012 to your computer and use it in GitHub Desktop.
Override the default WordPress oEmbed for YouTube Videos to always use the myCRED Video Shortcode.
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
/** | |
* Override WP oEmbed | |
* @version 1.0 | |
*/ | |
add_filter( 'embed_oembed_html', 'mycred_override_video_shortcode', 999, 4 ); | |
function mycred_override_video_shortcode( $original, $url, $attr, $post_ID ) { | |
// If myCRED is not enabled | |
if ( ! function_exists( 'mycred_render_shortcode_video' ) ) return $original; | |
// Get cache | |
$cachekey = '_mycred_' . md5( $url . serialize( $attr ) ); | |
$cache = get_post_meta( $post_ID, $cachekey, true ); | |
// If cache is set, return it now | |
if ( $cache !== '{{unknown}}' && ! empty( $cache ) ) | |
return $cache; | |
// If video id is not set | |
if ( ! isset( $attr['id'] ) || empty( $attr['id'] ) ) { | |
$video_id = ''; | |
if ( preg_match( '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $matches ) && isset( $matches[1] ) && ! empty( $matches[1] ) ) { | |
$video_id = $matches[1]; | |
} | |
$attr['id'] = $video_id; | |
} | |
// Return original embed if video id is not found | |
if ( $attr['id'] == '' ) return $original; | |
// Run the myCRED Video Shortcode | |
$html = mycred_render_shortcode_video( $attr ); | |
// Cache results | |
update_post_meta( $post_ID, $cachekey, $html ); | |
return $html; | |
} | |
/** | |
* Delete Video Cache | |
* @version 1.0 | |
*/ | |
add_action( 'pre_post_update', 'mycred_delete_oembed_caches' ); | |
function mycred_delete_oembed_caches( $post_ID ) { | |
$post_metas = get_post_custom_keys( $post_ID ); | |
if ( empty( $post_metas ) ) | |
return; | |
foreach( $post_metas as $post_meta_key ) { | |
if ( '_mycred_' == substr( $post_meta_key, 0, 8 ) ) | |
delete_post_meta( $post_ID, $post_meta_key ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment