0

I have a number custom field with a selector, I should select the number of bedrooms, when I edit the post the meta key value is saved correctly (I can see the number of bedrooms near the correspondent icon on the post) but if I reload the post editor page...the selection has disappeared, how can I fix the following code?

add_action( 'add_meta_boxes_post', "camere_add_meta_box" );
function camere_add_meta_box(){
    add_meta_box(
        "camere_meta_box",  // An ID for the Meta Box.  Make it unique to your plugin
        __( "Numero camere da letto", 'textdomain' ),  // The title for your Meta Box
        "camere_meta_box_render",  // A callback function to fill the Meta Box with the desired UI in the editor
        "post",  // The screen name - in this case the name of our custom post type
        "side"  // The context or placement for the meta box.  Choose "normal", "side" or "advanced"
    );
}
function camere_meta_box_render( $post ){
    $number = get_post_meta( $post->ID, "function_camere", true );
    echo '
    <div>
        <select name="function_camere">';
            for( $i = 0; $i < 13; $i++ ) {
                echo '<option value="'.$i.'">'.$i.'</option>';
            }
        echo '
        </select>
    </div>';
}
    
add_action( 'save_post', 'camere_meta_box_save');
function camere_meta_box_save( $post_id ) {
    if ($_POST['post_type'] == "post") {
        $number = $_POST['function_camere'];
        update_post_meta( $post_id, "function_camere", $number );
    }     
}

1 Answer 1

1

There's nothing in your code that would allow this to happen. In your HTML you need to add a selected attribute to the <option> element representing the current value. WordPress includes a helper function, selected() which can help with this:

function camere_meta_box_render( $post ){
    $number = get_post_meta( $post->ID, "function_camere", true );
    echo '<div><select name="function_camere">';
    for( $i = 0; $i < 13; $i++ ) {
    echo '<option value="'.$i.'" ' . selected( $i, $number, false ) . '>'.$i.'</option>';
    }
    echo '</select></div>';
}
1
  • My code has been modified Commented Aug 21, 2023 at 18:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.