主题开发文档

💡 云策文档标注

概述

本文档介绍了 WordPress 中音频嵌入功能,通过 [audio] 短码直接播放音频文件,支持多种格式如 mp3、ogg、wma、m4a 和 wav。文档涵盖了短码的基本用法、循环与自动播放选项、自定义样式方法以及相关技术参考。

关键要点

  • 使用 [audio] 短码嵌入音频文件,支持 mp3、ogg、wma、m4a 和 wav 格式。
  • 可通过 do_shortcode 函数在模板文件中动态调用短码。
  • 支持 loop 和 autoplay 选项控制音频循环和自动播放行为。
  • 可通过 CSS 类名 .wp-audio-shortcode 自定义音频播放器样式。
  • 提供了技术参考链接,如 WordPress 核心音频视频支持文档和 do_shortcode 函数。

代码示例

// 基本短码示例
[[audio src="music.mp3"]]

// 在模板文件中使用 do_shortcode
$music_file = get_template_directory_uri() . "/sounds/music.mp3";
echo do_shortcode('[[audio mp3=' . $music_file . ']]');

// 带循环和自动播放选项的短码
echo do_shortcode('[[audio mp3=' . $music_file . ' loop = "on" autoplay = 1]]');

// 自定义样式 CSS
.wp-audio-shortcode {
  width: 50%;
}

注意事项

  • 确保音频文件路径正确,避免因路径错误导致播放失败。
  • 使用 autoplay 选项时需考虑用户体验,避免自动播放干扰用户。
  • 自定义样式时,CSS 类名 .wp-audio-shortcode 是默认目标,确保样式规则正确应用。

📄 原文内容

Audio

You can directly embed audio files and play them back using a simple shortcode . Supported file types are mp3, ogg, wma, m4a and wav.

Audio shortcode

Following shortcode displays audio player that loads music.mp3 file:

[audio src="music.mp3"]

To use the shortcode from template file, use do_shortcode function. When music.mp3 file was stored in (theme_directory)/sounds directory, insert following code into your template file:

$music_file = get_template_directory_uri() . "/sounds/music.mp3"; 
echo do_shortcode('[audio mp3=' . $music_file . ']');

The shortcode creates the audio player as shown in the screenshot below.

Audio player

Loop and Autoplay

The following basic options are supported:

loop

Allows for the looping of media.

  • “off” – Do not loop the media. Default.
  • “on” – Media will loop to beginning when finished and automatically continue playing.

autoplay

Causes the media to automatically play as soon as the media file is ready.

  • 0 – Do not automatically play the media. Default.
  • 1 – Media will play as soon as it is ready.

The following example starts playing music immediately after the page load and loops.

echo do_shortcode('[audio mp3=' . $music_file . ' loop = "on" autoplay = 1]');

Styling

If you want to change the look & feel of audio player, you can do so by targeting the default class name of “wp-audio-shortcode”. If you insert following code into your style.css, half width of audio player will be displayed.

.wp-audio-shortcode {
  width: 50%;
}

Supported Audio format

  • mp3
  • ogg
  • wma
  • m4a
  • wav

References

For more technical details such as the internal library that enables this function, refer to