繁体   English   中英

WordPress使用选择更新用户元

[英]wordpress update user meta using select

尝试将我自己的自定义字段添加到用户配置文件。

使用update_user_meta时,我似乎无法正确地从$ _POST中获取数据。 但是,如果我使用字符串对值进行硬编码,则效果很好。 我知道$ _POST ['hub_group']内部的值可能是一个数组,我试过转换为字符串或只是引用第一个索引,但没有任何效果。

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 ) {
        if (isset($_POST['hub_group'])) {
            update_user_meta($user->ID, 'hub_group', $_POST['hub_group']);
        }       
        $hub_group = get_the_author_meta( 'hub_group', $user->ID);
    ?>
    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="twitter">PfAL Group</label></th>
            <td>
                <select name="hub_group" id="hub_group">
                  <option value="PfAL 1" <?php selected( $hub_group, "PfAL 1" ); ?>>PfAL 1</option>
                  <option value="PfAL 2" <?php selected( $hub_group, "PfAL 2" ); ?>>PfAL 2</option>
                  <option value="PfAL 3" <?php selected( $hub_group, "PfAL 3" ); ?>>PfAL 3</option>
                  <option value="PfAL 4" <?php selected( $hub_group, "PfAL 4" ); ?>>PfAL 4</option>
                </select>
            </td>
        </tr>
    </table>
<?php }

我设法通过划分更新和显示逻辑,然后将更新逻辑函数挂接到personal_options_updateedit_user_profile_update来解决此edit_user_profile_update 下面的代码对我有用,希望对您也一样!

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 ) {

    $hub_group = get_user_meta( $user->ID, 'hub_group' );

    ?>

    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="twitter">PfAL Group</label></th>
            <td>
                <select name="hub_group" id="hub_group">
                  <option value="PfAL 1" <?php selected( $hub_group[0], "PfAL 1" ); ?>>PfAL 1</option>
                  <option value="PfAL 2" <?php selected( $hub_group[0], "PfAL 2" ); ?>>PfAL 2</option>
                  <option value="PfAL 3" <?php selected( $hub_group[0], "PfAL 3" ); ?>>PfAL 3</option>
                  <option value="PfAL 4" <?php selected( $hub_group[0], "PfAL 4" ); ?>>PfAL 4</option>
                </select>
            </td>
        </tr>
    </table>

    <?php 

}

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; }

    update_user_meta( $user_id, 'hub_group', $_POST['hub_group'] );

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM