I have a custom meta-box for certain custom post types, and one of those fields in the meta-box is a drop down.
I am providing the field correctly, saving the information, and even calling it correctly (so I know it is being saved properly), however, when you return to edit the post, or update, the drop-down always has the first <select>
option listed, which I'm afraid my confuse some of the people editing these post types in the future.
For example, if an editor selects "Option 2", then hits Publish or Update, "Option 2" is saved and called in the loop, but the drop down immediately shows "Option 1" again.
Is there a way to have the 'selected' option that is saved be displayed on top, or at the top of the list, so it appears to the editor as saved?
My functions code :
function meta_options(){
global $post;
$custom = get_post_custom($post->ID);
$price = $custom["price"][0];
$selected = isset( $values['location'] ) ? esc_attr( $values['location'][0] ) :'';
?>
<label>Price:</label><input name="price" value="<?php echo $price; ?>" />
<label>Location : </label> <br />
<select name="location" id="location">
<option value="Option 1" <?php selected( $selected, 'Option 1' ); ?>>Option 1</option>
<option value="Option 2" <?php selected( $selected, 'Option 2' ); ?>>Option 2</option>
</select>
<?php } ?>
and then saving that information:
function save_price(){
global $post;
update_post_meta($post->ID, "price", $_POST["price"]);
update_post_meta( $post->ID, 'location', esc_attr( $_POST['location'] ));
}
Am I doing this correctly? Is there an easy way to accomplish this?
Many thanks.
<?php selected() ?>
is supposed to do this for me, but I'm not sure where my error is at this point then. If I'm saving the selection (because when I call the selected value in the loop, it's correct), why is the function not storing that value as$selected
and comparing it correctly using theselected()
function?