Skip to content

Instantly share code, notes, and snippets.

@wpexplorer
Last active September 24, 2020 23:44
Show Gist options
  • Save wpexplorer/cce8a00830af9d649afd4a0a7e219937 to your computer and use it in GitHub Desktop.
Save wpexplorer/cce8a00830af9d649afd4a0a7e219937 to your computer and use it in GitHub Desktop.
Advanced wp_oembed_get output for videos to add classes & params
// Function
function wpex_video_oembed( $video = '', $classes = '', $params = array() ) {
// Define output
$output = '';
// Sanitize URl
$video = esc_url( $video );
// Video required
if ( ! $video ) {
return;
}
// Fetch oemebed output
$html = wp_oembed_get( $video );
// Return if there is an error fetching the oembed code
if ( is_wp_error( $html ) ) {
return;
}
// Add classes
if ( $classes ) {
// Class attribute already added already via filter
if ( strpos( 'class="', $html ) ) {
$html = str_replace( 'class="', 'class="'. $classes .' ', $html );
}
// No class attribute found so lets add new one with our custom classes
else {
$html = str_replace( '<iframe', '<iframe class="'. $classes .'"', $html );
}
}
// Add params
if ( $params ) {
// Define params string
$params_string = '';
// Loop through and check vendors
foreach ( $params as $vendor => $params ) {
// Check initial video url for vendor (youtube/vimeo/etc)
if ( strpos( $video, $vendor ) ) {
// Loop through and add params to variable
foreach ( $params as $key => $val ) {
$params_string .= '&'. $key .'='. $val;
}
}
}
// Add params
if ( $params_string ) {
$html = str_replace( '?feature=oembed', '?feature=oembed'. $params_string, $html );
}
}
// Return output
return $html;
}
// Usage
echo wpex_video_oembed( 'VIDEO_URL', 'sp-video', array(
'youtube' => array(
'enablejsapi' => '1',
)
) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment