wp_video_shortcode() │ WP 3.6.0 Виводить HTML код відео за переданим посиланням на відео та інші параметри.
Це функція-обробник шоткода
, який використовується для відображення та відтворення відеофайлів у записах. Розмір плеєра визначається глобальною змінною темою $content_width (ширина макета шаблону). Також розмір плеєра можна вказати вручну.
Формати відео, які підтримує WordPress: mp4, m4v, webm, ogv, wmv, flv .
Приклади, як можна вставити відео в запис штатними методами WordPress:
Варіант 1 Можна вставити посилання (URL) на відео та не виділяти її жодними тегами – просто URL окремо на рядку:
Контент
http://my.movies.com/cool/movie/coolest.mov
Контент Варіант 2 Ми маємо пост із прикріпленим до нього відеофайлом і нам потрібно вивести цей відеофайл у пості. Тоді використовуємо шоткод:
Варіант 3 Ми маємо посилання на відео файл формату mp4, яке нам потрібно вставити в пост. Використовуємо шоткод із параметрами:
Варіант 4 У нас є посилання на відео файл та її альтернативи для форматів підтримуваних HTML5:
Повертає Строку|null
. HTML код для відображення відео.
Шаблон використання echo wp_video_shortcode([
'src' => '',
'poster' => '',
'loop' => '',
'autoplay' => '',
'preload' => 'metadata',
'height' => 360,
'width' => empty( $content_width ) ? 640 : $content_width,
'class' => '', // Атрибут 'class' для елемента `<video>`. За промовчанням 'wp-video-shortcode'
'id' => '', // Атрибут 'id' для елемента `<video>`. За промовчанням 'video-{$post_id}-{$instances}'.
]); Використання wp_video_shortcode($attr, $content); $attr (масив) Масив параметрів:
src (рядок) URL-відео файл. Якщо не вказати, буде отримано посилання на перше відео, прикріплене до посту. Можна використовувати такі значення, щоб визначити конкретний тип файлу, який потрібно отримати з прикріплених: mp4 , m4v , webm , ogv , wmv , flv . За замовчуванням: перший бачив файл, прикріплений до посту
poster (рядок) Посилання на зображення, яке буде показано замість відео, поки воно не програється. За замовчуванням: ”
loop (рядок) Зациклити програвання відео. Якщо поставити on
, відео буде програватися спочатку після закінчення. За замовчуванням: ‘off’
autoplay (рядок) Автоматично відтворювати показ відео після завантаження сторінки. За промовчанням: ‘off’ (відео не відтворюватиметься)
preload (рядок) Вказує, як потрібно підвантажувати відео під час завантаження сторінки. Може бути:
metadata
– Тільки метадані. За замовчуванням;none
– не підвантажувати відео;auto
– повністю підвантажувати відео під час завантаження сторінки.За замовчуванням: ‘metadata’
height (число) Вказує висоту відеоплеєра. Значення автоматично обчислюється під час завантаження файлу. Типово: висота медіафайлу
width (число) Ширина відео програвача. Значення автоматично обчислюється під час завантаження файлу. За замовчуванням: ширина медіафайлу
$class (string) Атрибут class елемента <video> . Default: ‘wp-video-shortcode’ За замовчуванням: попереднє встановлення
$content (рядок) Контент шоткод. Буде доданий наприкінці вбудованого тега <video> . За замовчуванням: ” Приклади #1 Припустимо, нам потрібно вивести відео в коді на окремій сторінці: echo wp_video_shortcode([
'src' => 'http://example.com/video/champion-2009.flv',
'poster' => 'http://example.com/img/champion-2009.jpg',
'height' => 400,
'width' => 600,
]); У результаті отримаємо такий код:
<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> Додати свій приклад
нотатки Global. int. $content_width список змін wp video shortcode WP 6.0.2 function wp_video_shortcode( $attr, $content = '' ) { global $content_width; $post_id = get_post()? get_the_ID() : 0; static $instance = 0; $instance++; /** * Filters default video shortcode output. * * Якщо фільтрований 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 replaced with shortcode markup. * @param array $attr Attributes of the shortcode. @see wp_video_shortcode() * @param string $content Video shortcode content. * @param int $instance Unique numeric ID з цього відео 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' => '', '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 ($ Video); $atts['src'] = wp_get_attachment_url( $video->ID ); if ( empty( $atts['src'] ) ) { return; } array_unshift( $default_types, 'src'); } /** * Filters the media library використані для відео shortcode. * * @ Since 3.6.0 * * @param string $library Media library використовуваний для відео 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 має з деякими URL-форматами для Vimeo and YouTube, // So update the URL to prevent the ME.js player від 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, немає потреби після #39686. $loop = $atts['loop']? '1': '0'; $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src ); } } /** * Filters class attribute для відео shortcode output container. * * @ Since 3.6.0 * @since 4.9.0 The `$atts` parameter was added. * * @param string $class CSS class або 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'] ), 'preload' => $atts['preload'], ); // Ці ones повинні бути омитані глибоко, якщо вони є бланк. foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) 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 ( false !== strpos( $content, "n" ) ) { $content = str_replace( array( "rn", "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 output of 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 використовуваний для відео shortcode. */ return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library); } Зв’язані функції