0

Trying to get both the hex and RGB value of a color from the native color picker in Wordpress, user chooses the color via a custom metabox in the admin. Just need to save both values as meta for re-use in the interface.

jQuery(function() {
    jQuery('.color-field').wpColorPicker();
});

Any feedback would be greatly appreciated. TXS.

1
  • You can get the RGB value via the change event: change: function ( event, ui ) { var rgb = ui.color.toCSS( 'rgb' ); ... } - see the "Advanced usage" section here and the Color.js docs.
    – Sally CJ
    Commented Oct 18, 2019 at 18:06

1 Answer 1

1

Thanks for your help Sally, here is the completed jQuery which pushes the RGB value to another field. Name of the RGB field has _rgb at the end.

jQuery(function() {
    var myOptions = {
        // you can declare a default color here,
        // or in the data-default-color attribute on the input
        defaultColor: false,
        // a callback to fire whenever the color changes to a valid color
        change: function(event, ui){
            var rgb = ui.color.toCSS( 'rgb' );
            var name = jQuery(this).attr("name");
            name = '#' + name + '_rgb';
            jQuery(name).val(rgb);
        },
        // a callback to fire when the input is emptied or an invalid color
        clear: function() {},
        // hide the color picker controls on load
        hide: true,
        // show a group of common colors beneath the square
        // or, supply an array of colors to customize further
        palettes: true
    };
    jQuery('.color-field-custom').wpColorPicker(myOptions);
});

And here is what the custom field looks like below the color picker field.

<input type="text" name="destination_secondary_color_rgb" id="destination_secondary_color_rgb" value="<?php echo get_post_meta($post->ID, 'destination_secondary_color_rgb', true); ?>" />
1
  • PS: You should escape dynamic values, and for input fields, you can use esc_attr() - e.g. <input name="foo" value="<?php echo esc_attr( get_option( 'foo' ) ); ?>"> :)
    – Sally CJ
    Commented Oct 20, 2019 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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