在用户配置文件中使用和保存自定义下拉框

时间:2017-07-27 作者:Anil Patidar

好的,我正在创建一个网站,需要一些用户配置文件自定义元字段的帮助。目前,我的职能如下。php文件:

//hooks
add_action( \'show_user_profile\', \'Add_user_fields\' );
add_action( \'edit_user_profile\', \'Add_user_fields\' );

function Add_user_fields( $user ) { ?>

<h3 class="sizeShapeH3">Select Chapters</h3>
<table class="form-table">
    <tr>
        <th><label for="dropdown">MPF Chapters </label></th>
        <td>
            <?php 
            //get dropdown saved value
            $selected = get_the_author_meta( \'user_top\', $user->ID ); //there was an extra ) here that was not needed 
            ?>
            <select name="user_top" id="user_top">
                <option value="MPF Pune Central:" <?php echo ($topselected == "MPF Pune Central:")?  \'selected="selected"\' : \'\' ?>>MPF Pune Central:</option>
                <option value="MPF Pune East:" <?php echo ($topselected == "MPF Pune East:")?  \'selected="selected"\' : \'\' ?>>MPF Pune East:</option>
                <option value="MPF Pune West:" <?php echo ($topselected == "MPF Pune West:")?  \'selected="selected"\' : \'\' ?>>MPF Pune West:</option>
                <option value="MPF Pune South:" <?php echo ($topselected == "MPF Pune South:")?  \'selected="selected"\' : \'\' ?>>MPF Pune South:</option>
                <option value="MPF PCMC:" <?php echo ($topselected == "MPF PCMC:")?  \'selected="selected"\' : \'\' ?>>MPF PCMC:</option>
            </select>
        </td>
    </tr>


</table>

<?php }

add_action( \'personal_options_update\', \'save_user_fields\' );
add_action( \'edit_user_profile_update\', \'save_user_fields\' );

function save_user_fields( $user_id ) {

    if ( !current_user_can( \'edit_user\', $user_id ) )
        return false;

    //save top
    update_usermeta( $user_id, \'user_chapters\', $_POST[\'user_chapters\'] );

}
所有的代码似乎都能工作,当我单击“更新配置文件”时,它也能工作(我想),但下拉菜单显示的是第一个项目,而不是用户选择的项目。因此,如果用户选择“Yoga Top”并单击“Save”(保存),“I get Guns”(我有枪)将显示,而不是用户选择的“Yoga Top”(瑜伽Top)。有什么我可以解决的吗?

我真的很感激任何帮助,因为我们在时间上已经迫在眉睫了。

1 个回复
SO网友:Johansson

您正在将数据存储在$selected 价值,而使用$topselected 在条件中检查选择了哪个值。

可以这样更改您的值:

$topselected= get_the_author_meta( \'user_top\', $user->ID ); 
OR 将内联条件更改为:

<option value="MPF Pune West:" <?php echo ($selected== "MPF Pune West:")?  \'selected="selected"\' : \'\' ?>>MPF Pune West:</option>
更新根据@birgire的评论,您可以使用内置selected() 功能:

<select name="user_top" id="user_top">
    <option value="MPF Pune Central:" <?php selected( $selected , "MPF Pune Central:" ); ?>>MPF Pune Central:</option>
    <option value="MPF Pune East:" <?php selected( $selected , "MPF Pune East:" ); ?>>MPF Pune East:</option>
    <option value="MPF Pune West:" <?php selected( $selected , "MPF Pune West:" ); ?>>MPF Pune West:</option>
    <option value="MPF Pune South:" <?php selected( $selected , "MPF Pune South:" ); ?>>MPF Pune South:</option>
    <option value="MPF PCMC:" <?php selected( $selected , "MPF PCMC:" ); ?>>MPF PCMC:</option>
</select>

结束