wp_video_shortcode()WP 3.6.0

Displays the video HTML code by specified video link and other parameters.

This is a handler function for [video] shortcode that is used to display and play video files in posts. The size of the video player depends on theme global variable $content_width (the width of the template layout). Also, the player size can be specified manually (in shortcode parameters).

Video formats supported by WordPress: mp4, m4v, webm, ogv, wmv, flv.

Examples of how to insert a video into a post using standard WordPress methods:

Method 1

You can insert a video link (URL on a single line) into post content:

Content

http://my.movies.com/cool/movie/coolest.mov

Content

Method 2

We have a post with an attached video file and we need to display this video file in the post content. Then we can use this shortcode:

[video]

Method 3

We have a link to a MP4 video file that we need to insert into the post. Use shortcode with parameters:

[video src="video-source.mp4"]

Method 4

We have a link to the video file and its alternatives HTML5 video formats:

[video mp4="source.mp4" ogv="source.ogv" mov="source.mov"]

Return

String|null. HTML content to display video.

Usage Template

echo wp_video_shortcode( [
	'src'      => '',
	'poster'   => '',
	'loop'     => '',
	'autoplay' => '',
	'preload'  => 'metadata',
	'height'   => 360,
	'width'    => empty( $content_width ) ? 640 : $content_width,
	'class'    => '', // 'class' attr for `<video>` element. Default 'wp-video-shortcode'
	'id'       => '', // 'id' attr for `<video>` element. Default 'video-{$post_id}-{$instances}'.
] );

Usage

wp_video_shortcode( $attr, $content );
$attr(array) (required)

Attributes of the shortcode.

  • src(string)
    URL to the video file. If don't specified, you will receive a link to the first video attached to the post. Use the following values to get the specific type of the attachments file: mp4, m4v, webm, ogv, wmv, flv.

    Default: first video file attached to the post

  • poster(string)
    A link to the image to represent the video until it is played.

  • loop(string)
    Do we need to loop the video playback? If on, then the video will be played again after the end.
    Default: 'off'

  • autoplay(string)
    Play the video automatically after the page loads.
    Default: 'off' (the video does not play)

  • preload(string)
    Specifies how to load the video when the page loads. Cen be:

    • metadata - only metadata. By default.
    • none - no any video load.
    • auto - load the video fully when the page loads.

    Default: 'metadata'

  • height(int)
    Specifies the height of the video player. The value is calculated automatically just after the file is loaded.
    Default: the video height

  • width(int)
    The width of the video player. The value is calculated automatically after the file is loaded.
    Default: the video width

  • $class(string)
    The class attribute for the <video> element.
    Default: 'wp-video-shortcode'

Default: presets

$content(string)
Shortcode content. Will be added to the end of <video> shortcode.
Default: ''

Examples

0

#1 Display the video on a specific page

Suppose we need to display a video (it has exactly the same functionality like a [video] shortcode because this function is a handler for it):

echo wp_video_shortcode( [
	'src'      => 'http://example.com/video/champion-2009.flv',
	'poster'   => 'http://example.com/img/champion-2009.jpg',
	'height'   => 400,
	'width'    => 600,
] );

As a result, we get this code:

<div style="width: 640px; max-width: 100%;">
	<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->
	<video class="wp-video-shortcode" id="video-2613-1" width="640" height="360" poster="http://example.com/img/champion-2009.jpg" preload="metadata" controls="controls">
		<source type="video/x-flv" src="http://example.com/video/champion-2009.flv" />
		<a href="http://example.com/video/champion-2009.flv">http://example.com/video/champion-2009.flv</a>
	</video>
</div>

Notes

  • Global. Int. $content_width

Changelog

Since 3.6.0 Introduced.

wp_video_shortcode() code WP 6.4.3

function wp_video_shortcode( $attr, $content = '' ) {
	global $content_width;
	$post_id = get_post() ? get_the_ID() : 0;

	static $instance = 0;
	++$instance;

	/**
	 * Filters the default video shortcode output.
	 *
	 * If the filtered output isn't empty, it will be used instead of generating
	 * the default video template.
	 *
	 * @since 3.6.0
	 *
	 * @see wp_video_shortcode()
	 *
	 * @param string $html     Empty variable to be replaced with shortcode markup.
	 * @param array  $attr     Attributes of the shortcode. See {@see wp_video_shortcode()}.
	 * @param string $content  Video shortcode content.
	 * @param int    $instance Unique numeric ID of this video shortcode instance.
	 */
	$override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );

	if ( '' !== $override ) {
		return $override;
	}

	$video = null;

	$default_types = wp_get_video_extensions();
	$defaults_atts = array(
		'src'      => '',
		'poster'   => '',
		'loop'     => '',
		'autoplay' => '',
		'muted'    => 'false',
		'preload'  => 'metadata',
		'width'    => 640,
		'height'   => 360,
		'class'    => 'wp-video-shortcode',
	);

	foreach ( $default_types as $type ) {
		$defaults_atts[ $type ] = '';
	}

	$atts = shortcode_atts( $defaults_atts, $attr, 'video' );

	if ( is_admin() ) {
		// Shrink the video so it isn't huge in the admin.
		if ( $atts['width'] > $defaults_atts['width'] ) {
			$atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
			$atts['width']  = $defaults_atts['width'];
		}
	} else {
		// If the video is bigger than the theme.
		if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
			$atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
			$atts['width']  = $content_width;
		}
	}

	$is_vimeo      = false;
	$is_youtube    = false;
	$yt_pattern    = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
	$vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';

	$primary = false;
	if ( ! empty( $atts['src'] ) ) {
		$is_vimeo   = ( preg_match( $vimeo_pattern, $atts['src'] ) );
		$is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );

		if ( ! $is_youtube && ! $is_vimeo ) {
			$type = wp_check_filetype( $atts['src'], wp_get_mime_types() );

			if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
				return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
			}
		}

		if ( $is_vimeo ) {
			wp_enqueue_script( 'mediaelement-vimeo' );
		}

		$primary = true;
		array_unshift( $default_types, 'src' );
	} else {
		foreach ( $default_types as $ext ) {
			if ( ! empty( $atts[ $ext ] ) ) {
				$type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
				if ( strtolower( $type['ext'] ) === $ext ) {
					$primary = true;
				}
			}
		}
	}

	if ( ! $primary ) {
		$videos = get_attached_media( 'video', $post_id );
		if ( empty( $videos ) ) {
			return;
		}

		$video       = reset( $videos );
		$atts['src'] = wp_get_attachment_url( $video->ID );
		if ( empty( $atts['src'] ) ) {
			return;
		}

		array_unshift( $default_types, 'src' );
	}

	/**
	 * Filters the media library used for the video shortcode.
	 *
	 * @since 3.6.0
	 *
	 * @param string $library Media library used for the video shortcode.
	 */
	$library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
	if ( 'mediaelement' === $library && did_action( 'init' ) ) {
		wp_enqueue_style( 'wp-mediaelement' );
		wp_enqueue_script( 'wp-mediaelement' );
		wp_enqueue_script( 'mediaelement-vimeo' );
	}

	/*
	 * MediaElement.js has issues with some URL formats for Vimeo and YouTube,
	 * so update the URL to prevent the ME.js player from breaking.
	 */
	if ( 'mediaelement' === $library ) {
		if ( $is_youtube ) {
			// Remove `feature` query arg and force SSL - see #40866.
			$atts['src'] = remove_query_arg( 'feature', $atts['src'] );
			$atts['src'] = set_url_scheme( $atts['src'], 'https' );
		} elseif ( $is_vimeo ) {
			// Remove all query arguments and force SSL - see #40866.
			$parsed_vimeo_url = wp_parse_url( $atts['src'] );
			$vimeo_src        = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];

			// Add loop param for mejs bug - see #40977, not needed after #39686.
			$loop        = $atts['loop'] ? '1' : '0';
			$atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
		}
	}

	/**
	 * Filters the class attribute for the video shortcode output container.
	 *
	 * @since 3.6.0
	 * @since 4.9.0 The `$atts` parameter was added.
	 *
	 * @param string $class CSS class or list of space-separated classes.
	 * @param array  $atts  Array of video shortcode attributes.
	 */
	$atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts );

	$html_atts = array(
		'class'    => $atts['class'],
		'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
		'width'    => absint( $atts['width'] ),
		'height'   => absint( $atts['height'] ),
		'poster'   => esc_url( $atts['poster'] ),
		'loop'     => wp_validate_boolean( $atts['loop'] ),
		'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
		'muted'    => wp_validate_boolean( $atts['muted'] ),
		'preload'  => $atts['preload'],
	);

	// These ones should just be omitted altogether if they are blank.
	foreach ( array( 'poster', 'loop', 'autoplay', 'preload', 'muted' ) as $a ) {
		if ( empty( $html_atts[ $a ] ) ) {
			unset( $html_atts[ $a ] );
		}
	}

	$attr_strings = array();
	foreach ( $html_atts as $k => $v ) {
		$attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
	}

	$html = '';

	if ( 'mediaelement' === $library && 1 === $instance ) {
		$html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
	}

	$html .= sprintf( '<video %s controls="controls">', implode( ' ', $attr_strings ) );

	$fileurl = '';
	$source  = '<source type="%s" src="%s" />';

	foreach ( $default_types as $fallback ) {
		if ( ! empty( $atts[ $fallback ] ) ) {
			if ( empty( $fileurl ) ) {
				$fileurl = $atts[ $fallback ];
			}
			if ( 'src' === $fallback && $is_youtube ) {
				$type = array( 'type' => 'video/youtube' );
			} elseif ( 'src' === $fallback && $is_vimeo ) {
				$type = array( 'type' => 'video/vimeo' );
			} else {
				$type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
			}
			$url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
			$html .= sprintf( $source, $type['type'], esc_url( $url ) );
		}
	}

	if ( ! empty( $content ) ) {
		if ( str_contains( $content, "\n" ) ) {
			$content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
		}
		$html .= trim( $content );
	}

	if ( 'mediaelement' === $library ) {
		$html .= wp_mediaelement_fallback( $fileurl );
	}
	$html .= '</video>';

	$width_rule = '';
	if ( ! empty( $atts['width'] ) ) {
		$width_rule = sprintf( 'width: %dpx;', $atts['width'] );
	}
	$output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );

	/**
	 * Filters the output of the video shortcode.
	 *
	 * @since 3.6.0
	 *
	 * @param string $output  Video shortcode HTML output.
	 * @param array  $atts    Array of video shortcode attributes.
	 * @param string $video   Video file.
	 * @param int    $post_id Post ID.
	 * @param string $library Media library used for the video shortcode.
	 */
	return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
}