I think it is just a matter of logic. If you don’t select any value, $_REQUEST['menu-item-custom-category'][$menu_item_db_id]
is empty. So, the next line delete_post_meta()
is never triggered in your code. Just think in the logic you need to know when to delete previous meta value.
For example:
if( !empty( $_REQUEST['menu-item-custom-category'][$menu_item_db_id] ) ) {
// Delete all previous values from database and save
// only the selected values in the current request
delete_post_meta( $menu_item_db_id, '_menu_item_custom_category' );
$values = $_REQUEST['menu-item-custom-category'][$menu_item_db_id];
if( is_array( $values ) ) {
// We have several values
// Sanitize values first (needed if you have not registered a sanitization callback with register_meta())
$values = array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) );
foreach( $values as $value ) {
add_post_meta( $menu_item_db_id, '_menu_item_custom_category', $value );
}
} else {
// We have single value
add_post_meta( $menu_item_db_id, '_menu_item_custom_category', sanitize_text_field( $values ) );
}
} else {
// All values unselected, delete all of them from post meta
delete_post_meta($menu_item_db_id, '_menu_item_custom_category');
}
This could be optimized, so only new values are added and only deselected values are deleted, without deleting and adding everything everytime. For example (based on this answer):
if ( empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {
// no values selected, delete all post meta for our key
delete_post_meta( $menu_item_db_id, '_menu_item_content_multiple' );
} else {
$old_values = get_post_meta( $menu_item_db_id, '_menu_item_custom_category' );
$new_values = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id]
$values_to_skip = array();
if( !empty( $old_values ) ) {
foreach( $old_values as $old_value ) {
if ( ! in_array( $old_value, $new_values ) ) {
// this value was in meta, but now it is not selected,
// so it has to be deletec
delete_post_meta( $menu_item_db_id, '_menu_item_custom_category', $old_value );
} else {
// This value was in meta and it is selected again,
// So, we don't need to save it again
$values_to_skip[] = $old_value;
}
}
}
// Get the values that are not already in database
// And store them
$values_to_save = array_diff( $new_values, $values_to_skip );
if ( ! empty( $values_to_save ) ) {
foreach ( $values_to_save as $value ) {
add_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $value );
}
}
}