prosenjit-itobuz
5/11/2017 - 1:14 PM

Advanced wp_oembed_get output for videos to add classes & params

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',
	)
) );