customization – how to add multi select or select 2 field to multiple select custom brand from user

Question

How to add a multi-select box meta box in the WordPress user section showing custom post type title.

Multiple select has been added using the following code

  //add meta filed in user in admin
add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
    <h3><?php _e("User Brand", "blank"); ?></h3>

    <table class="form-table">
    <tr>
        <th><label for="user_brand"><?php _e("Brand"); ?></label></th>
        <td>
            <?php
            
                $brand_id=get_user_meta( $user->ID, 'my_meta_box_select');
                
            ?>
                <select name="my_meta_box_select[]" id="my_meta_box_select" style="width: 400px;height: 140px;" multiple>
                      <option>Select Brand Here</option>
<?php
            $brand_item_arr = [];
            $brand_item_arr['select']='Select Here';
            $term_query = new WP_Term_Query( array( 
            'taxonomy' => 'pa_brand', 
            'hide_empty'             => false,
            ) );

            if ( ! empty( $term_query->terms ) ) 
            {
                foreach ( $term_query ->terms as $term ) 
                    {
                        
                        
                        
                        ?>
                        <option value="<?php echo $term->term_id; ?>" <?php if (in_array($term->term_id, $brand_id[0],false)){ ?> selected='selected' <?php  } ?> ><?php echo $term->name; ?></option>
                        <?php
                    }
            }
    

?>                  
                        
                        
                </select>
        </td>
    </tr>
    </table>
<?php }  
//https://wordpress.stackexchange.com/questions/214719/how-do-i-add-a-field-on-the-users-profile-for-example-country-age-etc
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) ) { 
        return false; 
    }
    $dat=$_POST['my_meta_box_select'];
    
    update_user_meta( $user_id, 'my_meta_box_select', $_POST['my_meta_box_select'] );
}

after that added jquery to make it select2

 jQuery('#my_meta_box_select').select2();

0
Amal 3 months 2021-05-17T11:11:17-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse