WordPress用户资料页如何增加用户性别或下拉框

追格官方小助手/ 2022年06月19日/ WordPress/ 浏览 1390

我们在做WordPress主题开发时,有时需额外为个人资料增加其他字段,如性别等,那么WordPress用户资料页,如何增加用户性别选择或下拉框呢?


添加以下代码到当前WordPress模板 functions.php 函数文件中即可


<?php
    add_action( 'show_user_profile', 'show_extra_profile_fields' );
    add_action( 'edit_user_profile', 'show_extra_profile_fields' );

    function show_extra_profile_fields( $user ) { ?>
        <h3>Extra profile information</h3>
        <table class="form-table">
            <tr>
                <th><label for="gender">Gender</label></th>
                <td>
                    <select name="gender" id="gender" >
                        <option value="Male" <?php selected( 'Male', get_the_author_meta( 'gender', $user->ID ) ); ?>>Male</option>
                        <option value="Female" <?php selected( 'Female', get_the_author_meta( 'gender', $user->ID ) ); ?>>Female</option>
                    </select>
                </td>
            </tr>
        </table>
    <?php }

    add_action( 'personal_options_update', 'save_extra_profile_fields' );
    add_action( 'edit_user_profile_update', 'save_extra_profile_fields' );

    function save_extra_profile_fields( $user_id ) {
        if ( !current_user_can( 'edit_user', $user_id ) )
            return false;

        //typo fix
        update_user_meta( $user_id, 'gender', $_POST['gender'] );
    }
?>


发表评论

暂无评论,抢个沙发...

客服 工单