函数文档

wp_is_local_html_output()

💡 云策文档标注

概述

wp_is_local_html_output() 函数用于检查给定的 HTML 字符串是否可能来自当前 WordPress 站点。它通过检测 HTML 中是否包含特定 WordPress 模式(如 RSD 或 REST API 链接)来判断,若无法确定则返回 null。

关键要点

  • 函数接受一个 HTML 字符串参数,返回布尔值或 null,表示 HTML 是否由当前站点生成或无法确定。
  • 检查逻辑基于 WordPress 核心动作是否启用,例如通过 has_action() 验证 wp_head 钩子上的 rsd_link 或 rest_output_link_wp_head。
  • 如果相关动作被禁用(例如通过第三方代码),函数可能返回 null,以避免误判。
  • 函数内部使用正则表达式处理 URL 模式,并检查 HTML 字符串是否包含这些模式。

代码示例

function wp_is_local_html_output( $html ) {
    // 1. Check if HTML includes the site's Really Simple Discovery link.
    if ( has_action( 'wp_head', 'rsd_link' ) ) {
        $pattern = preg_replace( '#^https?:(?=//)#', '', esc_url( site_url( 'xmlrpc.php?rsd', 'rpc' ) ) ); // See rsd_link().
        return str_contains( $html, $pattern );
    }

    // 2. Check if HTML includes the site's REST API link.
    if ( has_action( 'wp_head', 'rest_output_link_wp_head' ) ) {
        // Try both HTTPS and HTTP since the URL depends on context.
        $pattern = preg_replace( '#^https?:(?=//)#', '', esc_url( get_rest_url() ) ); // See rest_output_link_wp_head().
        return str_contains( $html, $pattern );
    }

    // Otherwise the result cannot be determined.
    return null;
}

注意事项

  • 此函数依赖于 WordPress 核心动作的启用状态,如果这些动作被移除或修改,可能影响检测准确性。
  • 返回 null 表示无法确定 HTML 来源,开发者应处理此情况以避免逻辑错误。
  • 函数自 WordPress 5.7.0 版本引入,使用时需确保环境兼容。

📄 原文内容

Checks whether a given HTML string is likely an output from this WordPress site.

Description

This function attempts to check for various common WordPress patterns whether they are included in the HTML string.
Since any of these actions may be disabled through third-party code, this function may also return null to indicate that it was not possible to determine ownership.

Parameters

$htmlstringrequired
Full HTML output string, e.g. from a HTTP response.

Return

bool|null True/false for whether HTML was generated by this site, null if unable to determine.

Source

function wp_is_local_html_output( $html ) {
	// 1. Check if HTML includes the site's Really Simple Discovery link.
	if ( has_action( 'wp_head', 'rsd_link' ) ) {
		$pattern = preg_replace( '#^https?:(?=//)#', '', esc_url( site_url( 'xmlrpc.php?rsd', 'rpc' ) ) ); // See rsd_link().
		return str_contains( $html, $pattern );
	}

	// 2. Check if HTML includes the site's REST API link.
	if ( has_action( 'wp_head', 'rest_output_link_wp_head' ) ) {
		// Try both HTTPS and HTTP since the URL depends on context.
		$pattern = preg_replace( '#^https?:(?=//)#', '', esc_url( get_rest_url() ) ); // See rest_output_link_wp_head().
		return str_contains( $html, $pattern );
	}

	// Otherwise the result cannot be determined.
	return null;
}

Changelog

Version Description
5.7.0 Introduced.