sinanisler logo

Custom Color Metabox, Custom Field, WordPress

Custom Field for Selecting Color per post.

Meta key is “color_meta_key”

function color_add_meta_box() {
    $posttypes = ['post'];  // you can add multiple post types here with commas '',''
    foreach ($posttypes as $posttype) {
        add_meta_box(
            'color_meta_box_id',
            'Color Meta Box',
            'color_meta_box_html',
            $posttype
        );
    }
}

add_action('add_meta_boxes', 'color_add_meta_box');

function load_color_picker_script() {
    wp_enqueue_style( 'wp-color-picker' );
    wp_enqueue_script( 'wp-color-picker' );
    add_action( 'admin_footer', 'color_picker_init_script' );
}

add_action( 'admin_enqueue_scripts', 'load_color_picker_script' );

function color_meta_box_html($post) {
    wp_nonce_field('color_meta_box_nonce', 'color_custom_nonce');
    $value = get_post_meta($post->ID, 'color_meta_key', true);
    echo '<label for="color_field">Color : </label> <br>';
    echo '<input type="text" id="color_field" name="color_field" value="' . esc_attr($value) . '" class="my-color-field" />';
}

function color_picker_init_script() {
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('.my-color-field').wpColorPicker();
        });
    </script>
    <?php
}

function color_save_postdata($post_id) {
    if (!isset($_POST['color_custom_nonce'])) {
        return;
    }
    if (!wp_verify_nonce($_POST['color_custom_nonce'], 'color_meta_box_nonce')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (isset($_POST['post_type']) && !current_user_can('edit_post', $post_id)) {
        return;
    }
    if (!isset($_POST['color_field'])) {
        return;
    }
    $my_data = sanitize_hex_color($_POST['color_field']);
    update_post_meta($post_id, 'color_meta_key', $my_data);
}

add_action('save_post', 'color_save_postdata');

Check this Metabox PHP Code Generator if you need it https://sinanisler.com/codex/create-custom-metabox-for-wordpress-post-types/

Recently made this code for the WooCommerce site for our agency geopard digital client.

Leave the first comment