6/1/15

WordPress - Thêm trường thông tin Vào user meta - Theme My Login

Ngoài các user fields mặc định như: email,name,first_name,last_name,… Ở ví dụ này chúng ta sẽ thêm field phone.



Sử dụng action show_user_profile và edit_user_profile để hiển thị user fields.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//custom user profile
//show và edit page
add_action('show_user_profile', 'my_show_extra_profile_fields');
add_action('edit_user_profile', 'my_show_extra_profile_fields');
function my_show_extra_profile_fields($user)
{
    $phone=get_the_author_meta('phone',$user->ID);
    ?>
    <table class="form-table">
            <tr>
                <td>phone number</td>
                <td><input type="text" name="phone" value="<?php echo $phone?>"/></td>
            </tr>
    </table>
    <?php
}
- Fields mới này chưa được lưu vào database, để lưu vào database sử dụng thêm đồng thời 2 action “personal_options_update” ,”edit_user_profile_update” để cập nhật fields.
1
2
3
4
5
6
7
8
9
10
//update user profile
add_action('personal_options_update', 'my_save_extra_profile_fields');
add_action('edit_user_profile_update', 'my_save_extra_profile_fields');
function my_save_extra_profile_fields($user_id)
{
    if (!current_user_can('edit_user', $user_id))
        return false;
    update_usermeta($user_id, 'phone', $_POST['phone']);    //update user profile
}
Plugin tạo avatar cho người dùng WP User Avatar là một ví dụ điển hình về cách tạo user meta field cho wordpress sử dụng tính năng này.
Cách khác bạn có thể tạo field cho user bằng cách tùy biến custom fields với plugin Advanced Custom Fields.
Plugin: https://wordpress.org/plugins/user-meta/screenshots/

Code: http://premiumcoding.com/add-custom-post-meta-field-wordpress-theme/

0 nhận xét: