函数文档

wp_oembed_add_discovery_links()

💡 云策文档标注

概述

wp_oembed_add_discovery_links() 函数用于在网站头部添加 oEmbed 发现链接,以支持内容嵌入功能。它通过检查当前是否为单篇文章且可嵌入,并应用过滤器来输出链接 HTML。

关键要点

  • 函数在 wp_head 动作中运行,添加 oEmbed 发现链接到网站头部。
  • 仅当 is_singular() 和 is_post_embeddable() 返回 true 时生成链接输出。
  • 使用 apply_filters('oembed_discovery_links', $output) 允许过滤输出 HTML。
  • 包含向后兼容性检查,防止在原始优先级重复运行。
  • 相关函数包括 is_post_embeddable()、get_oembed_endpoint_url() 等。

代码示例

function wp_oembed_add_discovery_links() {
    if ( doing_action( 'wp_head' ) ) {
        if ( ! has_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 ) ) {
            return;
        }
        remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
    }

    $output = '';
    if ( is_singular() && is_post_embeddable() ) {
        $output .= '' . "n";
        if ( class_exists( 'SimpleXMLElement' ) ) {
            $output .= '' . "n";
        }
    }
    echo apply_filters( 'oembed_discovery_links', $output );
}

注意事项

  • 从 WordPress 6.9.0 起,函数优先在 wp_head 优先级 4 运行,回退到优先级 10,以确保链接出现在前 150KB 内。
  • 6.8.0 版本调整了输出,仅当文章支持嵌入时才生成链接。
  • 函数在 4.4.0 版本引入,开发者应确保相关钩子和条件正确配置。

📄 原文内容

Adds oEmbed discovery links in the head element of the website.

Source

function wp_oembed_add_discovery_links() {
	if ( doing_action( 'wp_head' ) ) {
		// For back-compat, short-circuit if a plugin has removed the action at the original priority.
		if ( ! has_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 ) ) {
			return;
		}

		// Prevent running again at the original priority.
		remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
	}

	$output = '';

	if ( is_singular() && is_post_embeddable() ) {
		$output .= '<link rel="alternate" title="' . _x( 'oEmbed (JSON)', 'oEmbed resource link name' ) . '" type="application/json+oembed" href="' . esc_url( get_oembed_endpoint_url( get_permalink() ) ) . '" />' . "n";

		if ( class_exists( 'SimpleXMLElement' ) ) {
			$output .= '<link rel="alternate" title="' . _x( 'oEmbed (XML)', 'oEmbed resource link name' ) . '" type="text/xml+oembed" href="' . esc_url( get_oembed_endpoint_url( get_permalink(), 'xml' ) ) . '" />' . "n";
		}
	}

	/**
	 * Filters the oEmbed discovery links HTML.
	 *
	 * @since 4.4.0
	 *
	 * @param string $output HTML of the discovery links.
	 */
	echo apply_filters( 'oembed_discovery_links', $output );
}

Hooks

apply_filters( ‘oembed_discovery_links’, string $output )

Filters the oEmbed discovery links HTML.

Changelog

Version Description
6.9.0 Now runs first at wp_head priority 4, with a fallback to priority 10. This helps ensure the discovery links appear within the first 150KB.
6.8.0 Output was adjusted to only embed if the post supports it.
4.4.0 Introduced.