Home > Net >  Color Picker UI in WordPress settings API is not correct
Color Picker UI in WordPress settings API is not correct

Time:08-11

I need to have color picker settings filed in my plugin. I have registered a field and its saving value in the database correctly. But, in the admin area the picker user interface is not correct I think.

It should look like this: https://ibb.co/7XRHqqL

But in my case it's looking like this: https://ibb.co/vHvqmd0

Here is the code I have for registering the field

        add_settings_field( 'iconBg', 'Background Color', array( $this, 'bg_settings_field' ), 'wpfyscroller-settings-page', 'wpfyscrollersection' );
        register_setting( 'wpfyscrollerfields', 'iconBg', array('sanitize_callback'=>'sanitize_hex_color', 'default'=> '#000000') );

        //Callback function
        function bg_settings_field() { ?>
 
        
        <input type="text" name="iconBg" value="<?php echo get_option('iconBg') ?>"  >
         
    <?php }

Here is the code for enqueueing js

    add_action('admin_enqueue_scripts', array( $this, 'enqueue_admin_js' ) );
    function enqueue_admin_js() { 
 
        // Make sure to add the wp-color-picker dependecy to js file
        wp_enqueue_script( 'cpa_custom_js', plugins_url( '/assets/js/colorPicker.js', __FILE__ ), array( 'wp-color-picker' ), '', true  );
    }

NOTE: My 'jquery' dependency already loaded with another script.

Here is the JS code:

(function ($) {$(function () {

// Add Color Picker to all inputs that have 'color-field' class
$(".cpa-color-picker").wpColorPicker();});})(jQuery);

Not sure what mistake I did, any help will be apricated.

Thanks

CodePudding user response:

You can try the below code and hopefully work it. Your issue was on enqueue js.

/**
 * Enqueue style & scripts for color picker
 *
 * @return void
 */
function enqueue_admin_js() {

    // wp-color-picker 
    wp_enqueue_style( 'wp-color-picker' );

    // Make sure to add the wp-color-picker dependecy to js file
    wp_enqueue_script( 'cpa_custom_js', plugins_url( '/assets/js/colorPicker.js', __FILE__ ), array( 'wp-color-picker' ), '', true );
}
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_js' ) );
  • Related