wp_audio_shortcode() │ WP 3.6.0
Создает HTML код аудио плеера по указанной ссылке на аудио файл и параметрам вывода плеера.
Эта функцию лежит в основе аудио шорткодов WordPress и отвечает за вывод HTML кода плеера. Такой плеер позволяет прослушивать указанный аудио файл в браузере.
Функция создает HTML тег <audio> с необходимыми атрибутами. В код также добавляется резервный HTML для случаев, когда браузер не поддерживает <audio> тег.
По умолчанию, WordPress поддерживает следующие аудио форматы: mp3
, ogg
, wma
, m4a
, wav
.
Список поддерживаемых шорткодов в WordPress: [audio]
, [caption]
, [embed]
, [gallery]
, [playlist]
, [video]
. Подробнее про шорткоды .
Возвращает
Строку|null
. HTML тег <audio>
и дополнительный HTML код для резерва.
Использование
wp_audio_shortcode( $attr, $content );
$attr(массив) (обязательный)
Параметры обработки шорткода (вывода аудио). Могут быть:
src (строка)
URL на аудио файл. Поддерживаемые форматы: mp3
, ogg
, wma
, m4a
, wav
.
По умолчанию: '' (первый аудио файл прикрепленный к записи)
loop (true/false)
Зацикливание аудио. Атрибут 'loop' для тега <audio> . Может быть: on
или off
.
По умолчанию: ''
autoplay (true/false)
Авто-воспроизведение аудио. Атрибут 'autoplay' для тега <audio> . Может быть: on
или off
.
По умолчанию: ''
preload (строка)
Определяет как аудио должно загружаться при загрузке страницы. Атрибут 'preload' для тега <audio> . Может быть:
none
- не загружать аудио при загрузке страницы.
auto
- загружать аудио при загрузке страницы.
metadata
- загружать только метаданные файла.
По умолчанию: 'none'
class (строка)
Атрибут 'class' для тега <audio> .
По умолчанию: 'wp-audio-shortcode'
style (строка)
Атрибут 'style' для тега <audio> .
По умолчанию: 'width: 100%; visibility: hidden;'
Выглядит массив так:
$attr = array(
'src' => '',
'loop' => false,
'autoplay' => false,
'preload' => 'none',
'class' => 'wp-audio-shortcode',
'style' => 'width: 100%; visibility: hidden;'
);
$content(строка)
Контент шорткода. Передается в фильтр wp_audio_shortcode_override
в самом плеере не используется.
По умолчанию: ''
Об аудио шорткодах в WordPress
C версии 3.6 в WordPress можно использовать аудио шорткод. Выглядит он так: [audio]
. Можно указать параметры шорткода, так:
[audio src="http://example.com/my.mp3"]
Или так - включим зацикливание:
[audio src="http://example.com/my.mp3" loop="on"]
Или так, для резерва, когда браузер может не понимать указанный формат файла, укажем 3 разных формата:
[audio mp3="http://example.com/my.mp3" ogg="http://example.com/my.ogg" wav="http://example.com/my.wav"]
Или «встраивания» (embeds)
А можно записать еще проще, через так называемое «встраивание» (embeds) аудио файл можно вставить просто написав ссылку на него на отдельной строке. WP автоматически найдет и обработает такую ссылку, при этом не нужны никакие шорткоды. Т.е. можно написать так:
Текст до
http ://example.com/my.mp3
Текст после
Все эти варианты добавления аудио в запись, обрабатываются в итоге функцией wp_audio_shortcode() .
Примеры
#1 Выведем плеер аудио файла в любом месте шаблона
$args = array(
'src' => 'http://example.com/my.mp3',
'loop' => false,
'autoplay' => false,
'preload' => 'none'
);
echo wp_audio_shortcode( $args );
Выведет HTML код
<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
<audio class="wp-audio-shortcode" id="audio-7-1" preload="none" style="width: 100%; visibility: hidden;" controls="controls">
<source type="audio/mpeg" src="http://example.com/my.mp3?_=1" />
<a href="http://example.com/my.mp3">http://example.com/my.mp3</a>
</audio>
В браузере получим такой плеер, где можно включить и послушать указанный файл:
#2 Хук wp_audio_shortcode_override
Работу функции можно полностью переопределить через хук wp_audio_shortcode_override
. Точно также как это делается с шорткодом галереи в примере функции gallery_shortcode()
add_filter('wp_audio_shortcode_override', 'my_audio_shortcode', 10, 4);
function my_audio_shortcode( $empty_str, $attr, $content, $instance ){
// Проверяем что нам нужно, если подходит, то переопределяем всю функцию wp_audio_shortcode
if( $attr['autoplay'] ){
// тут пишем свой код вывода плеера, для музыки с авто-воспроизведением
}
else
return '';
}
Добавить свой пример
Список изменений
С версии 3.6.0
Введена.
С версии 6.8.0
Added the 'muted' attribute.
Код wp_audio_shortcode() wp audio shortcode
WP 6.8.1
function wp_audio_shortcode( $attr, $content = '' ) {
$post_id = get_post() ? get_the_ID() : 0;
static $instance = 0;
++$instance;
/**
* Filters the default audio shortcode output.
*
* If the filtered output isn't empty, it will be used instead of generating the default audio template.
*
* @since 3.6.0
*
* @param string $html Empty variable to be replaced with shortcode markup.
* @param array $attr Attributes of the shortcode. See {@see wp_audio_shortcode()}.
* @param string $content Shortcode content.
* @param int $instance Unique numeric ID of this audio shortcode instance.
*/
$override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
if ( '' !== $override ) {
return $override;
}
$audio = null;
$default_types = wp_get_audio_extensions();
$defaults_atts = array(
'src' => '',
'loop' => '',
'autoplay' => '',
'muted' => 'false',
'preload' => 'none',
'class' => 'wp-audio-shortcode',
'style' => 'width: 100%;',
);
foreach ( $default_types as $type ) {
$defaults_atts[ $type ] = '';
}
$atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
$primary = false;
if ( ! empty( $atts['src'] ) ) {
$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-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
}
$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 ) {
$audios = get_attached_media( 'audio', $post_id );
if ( empty( $audios ) ) {
return;
}
$audio = reset( $audios );
$atts['src'] = wp_get_attachment_url( $audio->ID );
if ( empty( $atts['src'] ) ) {
return;
}
array_unshift( $default_types, 'src' );
}
/**
* Filters the media library used for the audio shortcode.
*
* @since 3.6.0
*
* @param string $library Media library used for the audio shortcode.
*/
$library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
if ( 'mediaelement' === $library && did_action( 'init' ) ) {
wp_enqueue_style( 'wp-mediaelement' );
wp_enqueue_script( 'wp-mediaelement' );
}
/**
* Filters the class attribute for the audio 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 audio shortcode attributes.
*/
$atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts );
$html_atts = array(
'class' => $atts['class'],
'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
'loop' => wp_validate_boolean( $atts['loop'] ),
'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
'muted' => wp_validate_boolean( $atts['muted'] ),
'preload' => $atts['preload'],
'style' => $atts['style'],
);
// These ones should just be omitted altogether if they are blank.
foreach ( array( 'loop', 'autoplay', 'preload', 'muted' ) as $a ) {
if ( empty( $html_atts[ $a ] ) ) {
unset( $html_atts[ $a ] );
}
}
$attr_strings = array();
foreach ( $html_atts as $attribute_name => $attribute_value ) {
if ( in_array( $attribute_name, array( 'loop', 'autoplay', 'muted' ), true ) && true === $attribute_value ) {
// Add boolean attributes without a value.
$attr_strings[] = esc_attr( $attribute_name );
} elseif ( 'preload' === $attribute_name && ! empty( $attribute_value ) ) {
// Handle the preload attribute with specific allowed values.
$allowed_preload_values = array( 'none', 'metadata', 'auto' );
if ( in_array( $attribute_value, $allowed_preload_values, true ) ) {
$attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) );
}
} else {
// For other attributes, include the value.
$attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) );
}
}
$html = '';
if ( 'mediaelement' === $library && 1 === $instance ) {
$html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
}
$html .= sprintf( '<audio %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 ];
}
$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 ( 'mediaelement' === $library ) {
$html .= wp_mediaelement_fallback( $fileurl );
}
$html .= '</audio>';
/**
* Filters the audio shortcode output.
*
* @since 3.6.0
*
* @param string $html Audio shortcode HTML output.
* @param array $atts Array of audio shortcode attributes.
* @param string $audio Audio file.
* @param int $post_id Post ID.
* @param string $library Media library used for the audio shortcode.
*/
return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
}
Cвязанные функции