我认为这只是一个逻辑问题。如果未选择任何值,$_REQUEST[\'menu-item-custom-category\'][$menu_item_db_id]
为空。那么,下一行delete_post_meta()
在代码中从未触发。只需按照逻辑思考,您需要知道何时删除之前的元值。
例如:
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 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 );
}
}
}