I followed this tutorial to create a custom meta box with a simple two option drop down.
My code is below. The custom fields are saved when creating a post, and edit when I change the value and Update. But when I go to the edit post page the values aren't dynamic and displaying the correct drop down value based on the set meta value. So if I create a post and set the option to Yes, then I go edit to post it shows No but in the custom meta field it does show Yes so it's saving correctly. I know that the No
and Yes
values should be dynamic and check if any custom meta has been set to display it but not sure what the code is. Any help with the code is appreciated. Thanks
<?
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
add_meta_box('post_info', 'Trade', 'custom_post_info', 'post', 'side', 'high');
}
//Adds the actual option box
function custom_post_info() {
global $post;
?>
<fieldset id="mycustom-div">
<div>
<p>
<label for="cpi_dropdown_options" >Accept Trade?</label><br />
<select name="cpi_dropdown_options" id="cpi_dropdown_options">
<option <?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 1' ); ?>>No</option>
<option <?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 2' ); ?>>Yes</option>
</select>
<br />
</p>
</div>
</fieldset>
<?php
}
add_action('save_post', 'custom_add_save');
function custom_add_save($postID){
// called after a post or page is saved
if($parent_id = wp_is_post_revision($postID)) {
$postID = $parent_id;
}
if ($_POST['cpi_dropdown_options']) {
update_custom_meta($postID, $_POST['cpi_dropdown_options'], 'cpi_dropdown_options');
}
if ($_POST['cpi_text_option']) {
update_custom_meta($postID, $_POST['cpi_text_option'], 'cpi_text_option');
}
}
function update_custom_meta($postID, $newvalue, $field_name) {
// To create new meta
if(!get_post_meta($postID, $field_name)){
add_post_meta($postID, $field_name, $newvalue);
} else {
// or to update existing meta
update_post_meta($postID, $field_name, $newvalue);
}
}
?>