Austin Verburg Austin Verburg - 2 months ago 14
PHP Question

Get meta box to keep selection after update

I'm building a meta box for one of my custom post types that has a selection option. I'm trying to make it so that when you make a selection and update the post, the option stays selected when the page reloads. I've found a few people on StackOverflow working on the same and I've followed those suggestions but haven't quite figured it out yet. If anyone has any suggestions, any help is appreciated.

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

Answer

Shot in the dark here, but you are using the_ID() improperly. This function prints the ID to the screen. You are trying to return the ID for use as a function parameter. You should try something like:

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

See get_the_ID() vs the_ID()