W3cubDocs

/WordPress

sanitize_hex_color( string $color ): string|void

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.

© 2003–2024 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/sanitize_hex_color