get_media_embedded_in_content()
云策文档标注
概述
get_media_embedded_in_content() 函数用于从 HTML 内容中提取音频、视频、对象、嵌入或 iframe 标签。它通过正则表达式匹配指定类型的媒体元素,并返回一个包含这些元素的数组。
关键要点
- 函数检查 HTML 内容中的媒体标签,支持类型包括 'audio', 'video', 'object', 'embed', 'iframe'。
- 参数 $content 是必需的 HTML 字符串,$types 是可选的媒体类型数组,用于过滤返回结果。
- 使用 apply_filters('media_embedded_in_content_allowed_types', ...) 钩子允许开发者自定义允许的媒体类型。
- 返回值为字符串数组,包含匹配到的 HTML 媒体元素。
代码示例
function get_media_embedded_in_content( $content, $types = null ) {
$html = array();
$allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
if ( ! empty( $types ) ) {
if ( ! is_array( $types ) ) {
$types = array( $types );
}
$allowed_media_types = array_intersect( $allowed_media_types, $types );
}
$tags = implode( '|', $allowed_media_types );
if ( preg_match_all( '#' . $tags . ')[^[sS]*?|s*/>)#', $content, $matches ) ) {
foreach ( $matches[0] as $match ) {
$html[] = $match;
}
}
return $html;
}注意事项
- 正则表达式模式可能因内容格式而异,使用时需确保 HTML 结构正确以避免匹配错误。
- 如果 $types 参数为空,函数将使用默认的允许媒体类型列表。
- 此函数自 WordPress 3.6.0 版本引入,兼容性良好。
原文内容
Checks the HTML content for an audio, video, object, embed, or iframe tags.
Parameters
$contentstringrequired-
A string of HTML which might contain media elements.
$typesstring[]optional-
An array of media types:
'audio','video','object','embed', or'iframe'.Default:
null
Source
function get_media_embedded_in_content( $content, $types = null ) {
$html = array();
/**
* Filters the embedded media types that are allowed to be returned from the content blob.
*
* @since 4.2.0
*
* @param string[] $allowed_media_types An array of allowed media types. Default media types are
* 'audio', 'video', 'object', 'embed', and 'iframe'.
*/
$allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
if ( ! empty( $types ) ) {
if ( ! is_array( $types ) ) {
$types = array( $types );
}
$allowed_media_types = array_intersect( $allowed_media_types, $types );
}
$tags = implode( '|', $allowed_media_types );
if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[sS]*?</(?P=tag)>|s*/>)#', $content, $matches ) ) {
foreach ( $matches[0] as $match ) {
$html[] = $match;
}
}
return $html;
}
Hooks
- apply_filters( ‘media_embedded_in_content_allowed_types’, string[] $allowed_media_types )
-
Filters the embedded media types that are allowed to be returned from the content blob.
Changelog
| Version | Description |
|---|---|
| 3.6.0 | Introduced. |