2

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!

  • Please choose which of five questions you've asked should be answered. – Max Yudin Feb 23 '17 at 8:38
  • Sorry if I wasn't clear.. What's the ideal function for escaping a color value? – Tom Usborne Feb 23 '17 at 20:24
3

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.')';}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.