函数文档

wp_maybe_enqueue_oembed_host_js()

💡 云策文档标注

概述

wp_maybe_enqueue_oembed_host_js() 函数用于在页面包含文章嵌入时,有条件地加载 wp-embed 脚本。它通过检查提供的 HTML 是否包含特定嵌入标记来优化脚本加载,避免不必要的资源消耗。

关键要点

  • 函数检查 HTML 中是否包含 post embed 标记(如 wp-embedded-content),以决定是否加载 wp-embed 脚本。
  • 仅当 wp_oembed_add_host_js 动作已注册到 wp_head 钩子时,函数才会执行脚本加载逻辑。
  • 函数返回原始 HTML 字符串,不进行修改,确保嵌入内容正常显示。

代码示例

function wp_maybe_enqueue_oembed_host_js( $html ) {
    if (
        has_action( 'wp_head', 'wp_oembed_add_host_js' )
        &&
        preg_match( '/]*?wp-embedded-content/', $html )
    ) {
        wp_enqueue_script( 'wp-embed' );
    }
    return $html;
}

📄 原文内容

Enqueue the wp-embed script if the provided oEmbed HTML contains a post embed.

Description

In order to only enqueue the wp-embed script on pages that actually contain post embeds, this function checks if the provided HTML contains post embed markup and if so enqueues the script so that it will get printed in the footer.

Parameters

$htmlstringrequired
Embed markup.

Return

string Embed markup (without modifications).

Source

function wp_maybe_enqueue_oembed_host_js( $html ) {
	if (
		has_action( 'wp_head', 'wp_oembed_add_host_js' )
		&&
		preg_match( '/<blockquotes[^>]*?wp-embedded-content/', $html )
	) {
		wp_enqueue_script( 'wp-embed' );
	}
	return $html;
}

Changelog

Version Description
5.9.0 Introduced.