函数文档

sanitize_hex_color()

💡 云策文档标注

概述

sanitize_hex_color() 是 WordPress 中用于验证和清理十六进制颜色值的函数,确保输入符合 3 或 6 位带 # 的格式,防止不安全数据存储。

关键要点

  • 函数 sanitize_hex_color() 用于清理十六进制颜色字符串,返回空字符串、3 或 6 位带 # 的十六进制颜色,或不返回任何值。
  • 参数 $color 是必需的,类型为字符串,函数通过正则表达式验证颜色格式。
  • 对于不带 # 的颜色值,应使用 sanitize_hex_color_no_hash() 函数。
  • 该函数自 WordPress 3.4.0 版本引入,并在 4.6 版本后全局可用。
  • 常用于自定义设置的回调函数中,如 Customizer API 的 sanitize_callback。

代码示例

$wp_customize->add_setting( 'accent_color', array(
  'default' => '#f72525',
  'sanitize_callback' => 'sanitize_hex_color',
) );

注意事项

  • 在设置默认值和清理回调时,确保同时使用,以避免数据库存储不安全数据。
  • 注意区分 sanitize_hex_color() 和 sanitize_hex_color_no_hash() 的使用场景。

📄 原文内容

Sanitizes a hex color.

Description

Returns either ”, a 3 or 6 digit hex color (with #), or nothing.
For sanitizing values without a #, see sanitize_hex_color_no_hash() .

Parameters

$colorstringrequired

Return

string|void

Source

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

	// 3 or 6 hex digits, or the empty string.
	if ( preg_match( '|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) ) {
		return $color;
	}
}

Changelog

Version Description
3.4.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    It is usually most important to set the default value of the setting as well as its sanitization callback, which will ensure that no unsafe data is stored in the database.

    $wp_customize->add_setting( 'accent_color', array(
      'default' => '#f72525',
      'sanitize_callback' => 'sanitize_hex_color',
    ) );