函数文档

wp_oembed_add_provider()

💡 云策文档标注

概述

wp_oembed_add_provider() 函数用于向 WordPress 的 oEmbed 系统中添加一个 URL 格式与 oEmbed 提供者 URL 的配对。它允许开发者注册自定义的 oEmbed 提供者,以便 WordPress 能够自动嵌入来自特定 URL 格式的内容。

关键要点

  • 函数接受三个参数:$format(URL 格式,支持通配符)、$provider(oEmbed 提供者 URL)和 $regex(可选,指示 $format 是否为正则表达式,默认为 false)。
  • 函数内部根据 'plugins_loaded' 钩子是否已触发,选择直接操作 WP_oEmbed 对象或调用 WP_oEmbed::_add_provider_early() 方法。
  • 此函数从 WordPress 2.9.0 版本开始引入,是扩展 oEmbed 功能的核心工具。

代码示例

// 基本示例:使用通配符注册一个提供者
wp_oembed_add_provider( 'http://site.com/watchvideo/*', 'http://site.com/oembed/' );

// YouTube 示例:使用正则表达式注册(仅作示例,YouTube 默认已注册)
wp_oembed_add_provider( '#https?://(www.)?youtube.com/watch.*#i', 'https://www.youtube.com/oembed', true );

注意事项

  • URL 格式中可以使用星号作为通配符,但注意不要留空空格。
  • 如果 $regex 参数设置为 true,$format 应使用正则表达式格式。
  • YouTube 等常见提供者已由 WordPress 默认注册,开发者通常无需重复注册。

📄 原文内容

Adds a URL format and oEmbed provider URL pair.

Description

See also

Parameters

$formatstringrequired
The format of URL that this provider can handle. You can use asterisks as wildcards.
$providerstringrequired
The URL to the oEmbed provider.
$regexbooloptional
Whether the $format parameter is in a RegEx format.

Default:false

Source

function wp_oembed_add_provider( $format, $provider, $regex = false ) {
	if ( did_action( 'plugins_loaded' ) ) {
		$oembed                       = _wp_oembed_get_object();
		$oembed->providers[ $format ] = array( $provider, $regex );
	} else {
		WP_oEmbed::_add_provider_early( $format, $provider, $regex );
	}
}

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes