I know that sanitize_hex_color exists for sanitizing hexadecimal values going into the database (and only exists in the Customizer), but what’s the best function to escape those same values. Should I just use sanitize_hex_color? Is there a better performing function?

What about RGBA values?

Here’s a function I’m using to sanitize hex + rgba values right now:

function example_sanitize_rgba( $color ) {
    if ( '' === $color )
        return '';

    // If string does not start with 'rgba', then treat as hex
    // sanitize the hex color and finally convert hex to rgba
    if ( false === strpos( $color, 'rgba' ) ) {
        return sanitize_hex_color( $color );
    }

    // By now we know the string is formatted as an rgba color so we need to further sanitize it.
    $color = str_replace( ' ', '', $color );
    sscanf( $color, 'rgba(%d,%d,%d,%f)', $red, $green, $blue, $alpha );
    return 'rgba('.$red.','.$green.','.$blue.','.$alpha.')';

    return '';
}

Could I use this to escape the same values? What if there’s 100+ values on the page? Seems a little “heavy”.

Any input is greatly appreciated!

1 Answer
1

Just finished now the sanitize callback for RGBA colors.and tested in my theme and working perfect, and its taking RGBA values

please find the code

function awstheme_sanitize_rgba( $color ) {
    if ( empty( $color ) || is_array( $color ) )
        return 'rgba(0,0,0,0)';

    // If string does not start with 'rgba', then treat as hex
    // sanitize the hex color and finally convert hex to rgba
    if ( false === strpos( $color, 'rgba' ) ) {
        return sanitize_hex_color( $color );
    }

    // By now we know the string is formatted as an rgba color so we need to further sanitize it.
    $color = str_replace( ' ', '', $color );
    sscanf( $color, 'rgba(%d,%d,%d,%f)', $red, $green, $blue, $alpha );
    return 'rgba('.$red.','.$green.','.$blue.','.$alpha.')';}

Leave a Reply

Your email address will not be published. Required fields are marked *