函数文档

wp_embed_handler_youtube()

💡 云策文档标注

概述

wp_embed_handler_youtube() 是 WordPress 中用于处理 YouTube iframe 嵌入的回调函数,专门捕获无法通过 oEmbed 解析但可转换为可解析 URL 的 YouTube 嵌入链接。

关键要点

  • 函数作为 wp_embed_register_handler() 的回调,处理正则匹配到的 YouTube URL。
  • 参数包括 $matches(正则匹配数组)、$attr(嵌入属性)、$url(原始 URL)和 $rawattr(原始未修改属性)。
  • 返回嵌入 HTML,通过 wp_embed_handler_youtube 过滤器可自定义输出。
  • 内部使用 WP_Embed::autoembed() 将 URL 转换为可嵌入格式。

代码示例

function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
	global $wp_embed;
	$embed = $wp_embed->autoembed( sprintf( 'https://youtube.com/watch?v=%s', urlencode( $matches[2] ) ) );
	return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
}

注意事项

  • 自 WordPress 4.0.0 版本引入,用于增强 YouTube 嵌入的兼容性。
  • 适用于处理非标准或无法直接通过 oEmbed 解析的 YouTube 链接。

📄 原文内容

YouTube iframe embed handler callback.

Description

Catches YouTube iframe embed URLs that are not parsable by oEmbed but can be translated into a URL that is.

Parameters

$matchesarrayrequired
The RegEx matches from the provided regex when calling wp_embed_register_handler() .
$attrarrayrequired
Embed attributes.
$urlstringrequired
The original URL that was matched by the regex.
$rawattrarrayrequired
The original unmodified attributes.

Return

string The embed HTML.

Source

function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
	global $wp_embed;
	$embed = $wp_embed->autoembed( sprintf( 'https://youtube.com/watch?v=%s', urlencode( $matches[2] ) ) );

	/**
	 * Filters the YouTube embed output.
	 *
	 * @since 4.0.0
	 *
	 * @see wp_embed_handler_youtube()
	 *
	 * @param string $embed   YouTube embed output.
	 * @param array  $attr    An array of embed attributes.
	 * @param string $url     The original URL that was matched by the regex.
	 * @param array  $rawattr The original unmodified attributes.
	 */
	return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
}

Hooks

apply_filters( ‘wp_embed_handler_youtube’, string $embed, array $attr, string $url, array $rawattr )

Filters the YouTube embed output.

Changelog

Version Description
4.0.0 Introduced.