获取元框以在更新后保留选择

Get meta box to keep selection after update

我正在为我的自定义 post 类型之一构建一个元框,它有一个选择选项。我试图做到这一点,以便在您进行选择并更新 post 时,该选项在页面重新加载时保持选中状态。我发现 Whosebug 上有几个人在做同样的事情,我已经听从了这些建议,但还没有完全弄明白。如果有人有任何建议,我们将不胜感激。

<?php

function property_info_meta_box() {
    add_meta_box('property-info', 'Property', 'property_info_cb', 'properties', 'normal', 'high'); 
}
add_action('add_meta_boxes', 'property_info_meta_box');

function property_info_cb($propertyInfo) { 

    $selectAgent = get_post_meta($propertyInfo->ID, 'select-agent-value', true);

    ?>

    <label for="select-agent-text">Select Agent</label> <br>
    <select multiple size="5" name="select-agent" id="select-agent">

        <option value="none">None</option>

            <?php

            $args = array(
                'post_type' => 'agents',
                'posts_per_page' => -1
                );

            $posts = new WP_Query($args);

            if ( $posts->have_posts() ) : while ( $posts->have_posts() ) : $posts->the_post(); ?>

                <option value="<?php the_ID() ?>" <?php selected( $selectAgent, the_ID() ); ?>> <?php the_title(); ?> </option>

            <?php endwhile; endif; ?>

    </select>

<?php }

function add_property_info_fields ($propertyInfoId, $propertyInfo){
    if ($propertyInfo->post_type == 'properties') {

        if(isset($_POST['select-agent'])){
            update_post_meta($propertyInfoId, 'select-agent-value', $_POST['select-agent']);
        }

    }
}
add_action('save_post', 'add_property_info_fields', 10, 2);

这里是在黑暗中拍摄的,但您 the_ID() 使用不当。此函数将 ID 打印到屏幕上。您正在尝试 return 将 ID 用作函数参数。你应该尝试这样的事情:

<?php selected( $selectedAgent, get_the_ID() ); ?>

get_the_ID() vs the_ID()