WordPress - How can we create a "Custom Meta-box With Color Picker"?

Blow are the easy steps to create a custom meta-box with color picker in WordPress.
Step 1 – Register Custom Meta-box
1
2
3
4
5
function aft_add_meta_box() {
    add_meta_box('aft_sectionid', 'Post Background', 'aft_meta_box_callback', 'post');
}
 
add_action( 'add_meta_boxes', 'aft_add_meta_box' );
Step 2 – Creating Custom Metabox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function aft_meta_box_callback( $post ) {
    wp_nonce_field( 'aft_meta_box', 'aft_meta_box_nonce' );
    $color = get_post_meta( $post->ID, 'country_bg_color', true );
    ?>
    <script>
    (function( $ ) {
        // Add Color Picker to all inputs that have 'color-field' class
        $(function() {
        $('.color-field').wpColorPicker();
        });
    })( jQuery );
    </script>
    <div class="custom_meta_box">
<label>Select Post Background Color: </label>
    <input class="color-field" name="country_bg_color" type="text" value="<?php if($color !=''){ echo '#'.$color; } ?>">
    <br>
<div class="clear">
</div>
</div>
<?php
}
Step 3 –Saving Metabox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function aft_save_meta_box_data( $post_id ) {
    if ( !isset( $_POST['aft_meta_box_nonce'] ) ) {
        return;
    }
 
    if ( !wp_verify_nonce( $_POST['aft_meta_box_nonce'], 'aft_meta_box' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( !current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    
    $country_bg_color = ( isset( $_POST['country_bg_color'] ) ? sanitize_html_class( $_POST['country_bg_color'] ) : '' );
    update_post_meta( $post_id, 'country_bg_color', $country_bg_color );
}
add_action( 'save_post', 'aft_save_meta_box_data' );

No comments:

Post a Comment