maybe_hash_hex_color()WP 3.4.0

Ensures that any hex color is properly hashed. Otherwise, returns value untouched.

This method should only be necessary if using sanitize_hex_color_no_hash().

No Hooks.

Returns

String. The color with the hash prefix if it's a valid hex color, otherwise the original value.

Usage

maybe_hash_hex_color( $color );
$color(string) (required)
The color value to add the hash prefix to. Can be with or without a #.

Changelog

Since 3.4.0 Introduced.

maybe_hash_hex_color() code WP 6.9.1

function maybe_hash_hex_color( $color ) {
	$unhashed = sanitize_hex_color_no_hash( $color );
	if ( $unhashed ) {
		return '#' . $unhashed;
	}

	return $color;
}