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

时间:2016-09-30 21:26:02

标签: php wordpress select meta-boxes

我正在构建一个具有选择选项的自定义帖子类型的元框。我正在尝试这样做,以便当您进行选择并更新帖子时,该选项在页面重新加载时保持选中状态。我发现StackOverflow上的一些人正在进行同样的工作,我已经遵循了这些建议,但还没有完全弄明白。如果有人有任何建议,我们将不胜感激。

<?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);

1 个答案:

答案 0 :(得分:0)

在黑暗中拍摄,但你使用the_ID()不正确。此功能将ID打印到屏幕。您正在尝试返回ID以用作函数参数。你应该尝试类似的东西:

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

请参阅get_the_ID() vs the_ID()