函数文档

sanitize_hex_color_no_hash()

💡 云策文档标注

概述

sanitize_hex_color_no_hash() 函数用于清理不带井号 (#) 的十六进制颜色值,返回清理后的值或空字符串/null。建议优先使用 sanitize_hex_color() 函数。

关键要点

  • 清理输入的颜色字符串,移除开头的井号 (#)。
  • 返回值为清理后的 3 位或 6 位十六进制颜色(不带井号),空字符串(如果输入为空),或 null(如果无效)。
  • 参数 $color 为必需,可以是带或不带井号的颜色值。
  • 函数内部调用 sanitize_hex_color() 进行验证,确保颜色有效性。
  • 自 WordPress 3.4.0 版本引入。

代码示例

function sanitize_hex_color_no_hash( $color ) {
	$color = ltrim( $color, '#' );

	if ( '' === $color ) {
		return '';
	}

	return sanitize_hex_color( '#' . $color ) ? $color : null;
}

注意事项

存储不带井号的十六进制颜色会增加 UI 添加井号的负担,且不利于升级到其他颜色类型(如 rgba、hsl、rgb 或 HTML 颜色名称)。


📄 原文内容

Sanitizes a hex color without a hash. Use sanitize_hex_color() when possible.

Description

Saving hex colors without a hash puts the burden of adding the hash on the UI, which makes it difficult to use or upgrade to other color types such as rgba, hsl, rgb, and HTML color names.

Returns either ”, a 3 or 6 digit hex color (without a #), or null.

Parameters

$colorstringrequired
The color value to sanitize. Can be with or without a #.

Return

string|null The sanitized hex color without the hash prefix, empty string if input is empty, or null if invalid.

Source

function sanitize_hex_color_no_hash( $color ) {
	$color = ltrim( $color, '#' );

	if ( '' === $color ) {
		return '';
	}

	return sanitize_hex_color( '#' . $color ) ? $color : null;
}

Changelog

Version Description
3.4.0 Introduced.