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