Skip to main content
2 of 3
edited tags

Wordpress Custom Fields Won't Save

I've created two custom post types 'buildings' and 'availabilities' and added a query on availabilities to select what building it belongs too but I can't seem to get it to save.

 add_action('admin_init', 'p2p2_add_building_metabox');

function p2p2_add_building_metabox(){
add_meta_box( 
    'building_availability', 
    __('Building', 'bandpress'), 
    'p2p2_building_availability_metabox', 
    'availabilities', 
    'side', 
    'default', 
    array( 'id' => 'p2p2_building') 
);}
   function p2p2_building_availability_metabox($post, $args){
wp_nonce_field( plugin_basename( __FILE__ ), 'p2p2_building_nonce' );
$building_id = get_post_meta($post->ID, 'p2p2_building', true);

echo "<p>Select The Building of This Availability</p>";
echo "<select id='p2p2_building' name='p2p2_building'>";
// Query the buildings here
$query = new WP_Query( 'post_type=building' );
while ( $query->have_posts() ) {
    $query->the_post();
    $id = get_the_ID();
    $selected = "";

    if($id == $author_id){
        $selected = ' selected="selected"';
    }
    echo '<option' . $selected . ' value=' . $id . '>' . get_the_title() . '</option>'; } echo "</select>"; }
 
 add_action('save_post', 'p2p2_save_building_metabox', 1, 2);
 function p2p2_save_building_metabox($post_id, $post){
// Don't wanna save this now, right?
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return;
if ( !isset( $_POST['p2p2_building_nonce'] ) )
    return;
if ( !wp_verify_nonce( $_POST['p2p2_building_nonce'], plugin_basename( __FILE__ ) ) )
    return;

// We do want to save? Ok!
$key = 'p2p2_building';
$value = $_POST["p2p2_building"];
if ( get_post_meta( $post->ID, $key, FALSE ) ) { // If the custom field already has a value
    update_post_meta( $post->ID, $key, $value );
} else { // If the custom field doesn't have a value
    add_post_meta( $post->ID, $key, $value );
}
if ( !$value ) delete_post_meta( $post->ID, $key ); // Delete if blank }