How to Use WordPress’s Iris Colorpicker on the Front End

I learned a few things today: first, that WordPress has a built-in colorpicker called Iris, and second, that you can use it on the front end of your website if you need custom colorpicker functionality.

Iris is evidently actually designed for admin options pages, and so it’s usually included via WordPress’s admin_enqueue_scripts() calls, as explained in its main documentation (actually a release note from WordPress 3.5 when it was added).

Including the Iris colorpicker on the front end is not as easy as simply changing admin_enqueue_scripts() to wp_enqueue_scripts(). Fortunately, as always, Stack Exchange has an amazing perfect-fitting answer. Please visit the linked thread for the explanation, and here’s the code snippet itself, with comments added:

add_action( 'wp_enqueue_scripts', 'wpa82718_scripts', 100 );
function wpa82718_scripts() {
    // Enqueuing CSS stylesheet for Iris (the easy part)
    wp_enqueue_style( 'wp-color-picker' );

    // Manually enqueing Iris itself by linking directly
    //    to it and naming its dependencies
    wp_enqueue_script(
        'iris',
        admin_url( 'js/iris.min.js' ),
        array( 
            'jquery-ui-draggable', 
            'jquery-ui-slider', 
            'jquery-touch-punch'
        ),
        false,
        1
    );

    // Now we can enqueue the color-picker script itself, 
    //    naming iris.js as its dependency
    wp_enqueue_script(
        'wp-color-picker',
        admin_url( 'js/color-picker.min.js' ),
        array( 'iris' ),
        false,
        1
    );

    // Manually passing text strings to the JavaScript
    $colorpicker_l10n = array(
        'clear' => __( 'Clear' ),
        'defaultString' => __( 'Default' ),
        'pick' => __( 'Select Color' ),
        'current' => __( 'Current Color' ),
    );
    wp_localize_script( 
        'wp-color-picker',
        'wpColorPickerL10n', 
        $colorpicker_l10n 
    ); 
}

Enjoy being able to use WordPress’s awesome built-in colorpicker on the front end!

Image credit: evelynishere


1 Response

Comments

  • Praveen says:

    How to use this in Front end..? I added your code in the theme/functions.php and I want to know how to use this in front end. I am not expertise in wordpress so I am asing.

Add a Comment

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