函数文档

wp_normalize_path()

💡 云策文档标注

概述

wp_normalize_path() 是 WordPress 核心函数,用于标准化文件系统路径,确保跨平台兼容性。它主要处理 Windows 系统中的反斜杠替换、驱动器字母大写化,并减少重复斜杠,同时支持网络共享路径。

关键要点

  • 标准化路径:将反斜杠()替换为正斜杠(/),强制 Windows 驱动器字母大写,并减少重复斜杠为单个。
  • 参数:接受一个字符串参数 $path,表示要标准化的路径。
  • 返回值:返回标准化后的路径字符串。
  • 跨平台支持:特别针对 Windows 系统优化,包括网络共享路径(允许两个前导斜杠)。
  • 流包装器处理:如果路径是流 URL(如 php://),函数会分离包装器部分并保留。
  • 相关函数:与 wp_is_stream() 配合使用,检测流路径。
  • 版本历史:自 WordPress 3.9 引入,后续版本增加了对 Windows 网络共享、驱动器字母大写和 PHP 文件包装器的支持。

代码示例

$bS_incl_path = get_template_directory() . '/inc';

if(function_exists('wp_normalize_path')){
    $bS_incl_path = wp_normalize_path($bS_incl_path);
}

define('THM_INC', $bS_incl_path);
require_once (THM_INC. '/wp_bootstrap_navwalker.php');

注意事项

  • 函数主要用于确保路径在 Windows 和 Unix 系统间的一致性,避免因路径分隔符差异导致的错误。
  • 在调用前,建议使用 function_exists() 检查函数可用性,以兼容旧版本 WordPress。
  • 示例展示了如何标准化主题包含路径,提高代码可移植性。

📄 原文内容

Normalizes a filesystem path.

Description

On windows systems, replaces backslashes with forward slashes and forces upper-case drive letters.
Allows for two leading slashes for Windows network shares, but ensures that all other duplicate slashes are reduced to a single.

Parameters

$pathstringrequired
Path to normalize.

Return

string Normalized path.

Source

function wp_normalize_path( $path ) {
	$wrapper = '';

	if ( wp_is_stream( $path ) ) {
		list( $wrapper, $path ) = explode( '://', $path, 2 );

		$wrapper .= '://';
	}

	// Standardize all paths to use '/'.
	$path = str_replace( '\', '/', $path );

	// Replace multiple slashes down to a singular, allowing for network shares having two slashes.
	$path = preg_replace( '|(?<=.)/+|', '/', $path );

	// Windows paths should uppercase the drive letter.
	if ( ':' === substr( $path, 1, 1 ) ) {
		$path = ucfirst( $path );
	}

	return $wrapper . $path;
}

Changelog

Version Description
4.9.7 Allows for PHP file wrappers.
4.5.0 Allows for Windows network shares.
4.4.0 Ensures upper-case drive letters on Windows systems.
3.9.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example

    A Simple example to normalize the theme include path

        $bS_incl_path = get_template_directory() . '/inc';
    
        /**
         * Define theme include path
         * 
         * Normalize the include path to be safe on windows hosts
         * @return string Normalized path
         * require min WordPress version 3.9
         * @since boot_Strap 1.0.1
         * 
         */
    
         if(function_exists('wp_normalize_path')){
             
            $bS_incl_path = wp_normalize_path($bS_incl_path);
         }
        
        define('THM_INC', $bS_incl_path);
    
        require_once (THM_INC. '/wp_bootstrap_navwalker.php');   

    print_r($bS_incl_path); shows

    Using this function:

    C:/xampp/htdocs/boot_strap/wp-content/themes/boot_Strap/inc

    Without this function:

    C:xampphtdocsboot_strap/wp-content/themes/boot_Strap/inc

    On a Windows server.