1

我在前端用户个人资料上创建了一个下拉选择,其中包括所有自定义帖子类型的帖子。

选择它实际上并没有保存选择,它只是恢复到第一个选项。

我哪里错了?

这是我的 functions.php 文件中的代码:

add_action( 'personal_options_update', 'save_custom_profile_fields' );
add_action( 'edit_user_profile_update', 'save_custom_profile_fields' );
function save_custom_profile_fields( $user_id ) {
    update_user_meta( $user_id, 'teampage', $_POST['teampage'], get_user_meta( $user_id, 'teampage', true ) );
}

add_action( 'personal_options', 'add_profile_options');
function add_profile_options( $profileuser ) {
    $greeting = get_user_meta($profileuser->ID, 'teampage', true);
    ?><tr>
    <th scope="row">Member of which Health Board?</th>
    <td>
        <select name="teampage" id="teampage" >
            <?php $portfolioloop = new WP_Query( array( 
                'post_type' => 'board', 
                'post_status' => 'publish'
            )); ?>
            <?php while ( $portfolioloop->have_posts() ) : $portfolioloop->the_post(); ?>  
                <option id="Yes" <?php selected( $profileuser->teampage, 'Yes' ); ?>><?php echo the_title(); ?></option> 
            <?php endwhile; wp_reset_query(); wp_reset_postdata(); ?>
        </select>
    </td>
    </tr><?php
}

我正在使用本教程

4

1 回答 1

1

我发现你的问题是什么。这是你犯的几个小错误。这是工作代码:

add_action( 'personal_options_update', 'save_custom_profile_fields' );
add_action( 'edit_user_profile_update', 'save_custom_profile_fields' );
function save_custom_profile_fields( $user_id ) {
    update_user_meta( $user_id, 'teampage', $_POST['teampage'], get_user_meta( $user_id, 'teampage', true ) );
}

add_action( 'personal_options', 'add_profile_options');
function add_profile_options( $profileuser ) {
    $greeting = get_user_meta($profileuser->ID, 'teampage', true);
    ?><tr>
    <th scope="row">Member of which Health Board?</th>
    <td>
        <select name="teampage" id="teampage" >
            <?php $portfolioloop = new WP_Query( array( 
                'post_type' => 'board', 
                'post_status' => 'publish'
            ));
            global $post; ?>
            <?php while ( $portfolioloop->have_posts() ) : $portfolioloop->the_post(); ?>  
                <option <?php selected( $profileuser->teampage, $post->ID ); ?> value="<?php echo $post->ID; ?>"><?php echo the_title(); ?></option> 
            <?php endwhile; wp_reset_query(); wp_reset_postdata(); ?>
        </select>
    </td>
    </tr><?php
}

您忘记将value属性添加到每个option.

此外,您不应该检查所有选项的相同值(您使用selected( $profileuser->teampage, 'Yes' );,它本质上检查值是否$profileuser->teampageYes)。相反,我们将帖子 ID 分配给每个选项并进行检查。

于 2012-11-23T15:55:53.973 回答