函数文档

wp_register_plugin_realpath()

💡 云策文档标注

概述

wp_register_plugin_realpath() 函数用于注册插件的真实路径,主要用于解决符号链接路径问题,在 plugin_basename() 中调用。

关键要点

  • 函数接受一个必需参数 $file,表示已知的文件路径,返回布尔值指示路径是否成功注册。
  • 通过全局变量 $wp_plugin_paths 存储插件路径到真实路径的映射,以处理符号链接情况。
  • 使用 wp_normalize_path() 进行路径规范化,并静态缓存 WP_PLUGIN_DIR 和 WPMU_PLUGIN_DIR 的规范化值以提高性能。
  • 如果插件路径与 WP_PLUGIN_DIR 或 WPMU_PLUGIN_DIR 相同,则返回 false;如果插件路径与真实路径不同,则注册映射并返回 true。

代码示例

function wp_register_plugin_realpath( $file ) {
	global $wp_plugin_paths;

	// Normalize, but store as static to avoid recalculation of a constant value.
	static $wp_plugin_path = null, $wpmu_plugin_path = null;

	if ( ! isset( $wp_plugin_path ) ) {
		$wp_plugin_path   = wp_normalize_path( WP_PLUGIN_DIR );
		$wpmu_plugin_path = wp_normalize_path( WPMU_PLUGIN_DIR );
	}

	$plugin_path     = wp_normalize_path( dirname( $file ) );
	$plugin_realpath = wp_normalize_path( dirname( realpath( $file ) ) );

	if ( $plugin_path === $wp_plugin_path || $plugin_path === $wpmu_plugin_path ) {
		return false;
	}

	if ( $plugin_path !== $plugin_realpath ) {
		$wp_plugin_paths[ $plugin_path ] = $plugin_realpath;
	}

	return true;
}

注意事项

  • 此函数自 WordPress 3.9.0 版本引入,主要用于内部处理,开发者通常无需直接调用。
  • 相关函数包括 wp_normalize_path(),用于路径规范化;在 uninstall_plugin() 和 plugin_sandbox_scrape() 中被使用。

📄 原文内容

Register a plugin’s real path.

Description

This is used in plugin_basename() to resolve symlinked paths.

See also

Parameters

$filestringrequired
Known path to the file.

Return

bool Whether the path was able to be registered.

Source

function wp_register_plugin_realpath( $file ) {
	global $wp_plugin_paths;

	// Normalize, but store as static to avoid recalculation of a constant value.
	static $wp_plugin_path = null, $wpmu_plugin_path = null;

	if ( ! isset( $wp_plugin_path ) ) {
		$wp_plugin_path   = wp_normalize_path( WP_PLUGIN_DIR );
		$wpmu_plugin_path = wp_normalize_path( WPMU_PLUGIN_DIR );
	}

	$plugin_path     = wp_normalize_path( dirname( $file ) );
	$plugin_realpath = wp_normalize_path( dirname( realpath( $file ) ) );

	if ( $plugin_path === $wp_plugin_path || $plugin_path === $wpmu_plugin_path ) {
		return false;
	}

	if ( $plugin_path !== $plugin_realpath ) {
		$wp_plugin_paths[ $plugin_path ] = $plugin_realpath;
	}

	return true;
}

Changelog

Version Description
3.9.0 Introduced.