如何将多选菜单中的每个选项保存为自己的meta\\u键+meta\\u值对?
这是基本的多选菜单。注意:多个选择菜单允许您选择多个选项。
<select name="products[]" multiple>
<option value="1">Product One</option>
<option value="2">Product Two</option>
<option value="3">Product Three</option>
.... etc
</select>
中的代码位
save_post
我需要帮助的功能。
if ( isset( $_POST[ \'products\' ] ) ) {
foreach ( $_POST[ \'products\' ] as $product ) {
// this would just keep adding the products as separate meta keys, which is what I want, but I need to modify it so it deletes them when they are unselected.
add_post_meta( $post_id, \'products\', $product, false );
}
}
我希望每个选项都是自己的元键和值对,而不是序列化数组。如果更新了多选菜单,我希望不再从Posteta表中选择旧值
delete_post_meta
.
例如,wp\\U Posteta表如下所示:
post_id meta_key meta_value
45 products 2
63 products 3
12 products 1
最合适的回答,由SO网友:gmazzap 整理而成
在里面试试这个save_post
但请注意代码是not 已测试
$old = get_post_meta($post_id, \'products\');
$new = isset ( $_POST[\'products\'] ) ? $_POST[\'products\'] : array();
if ( empty ($new) ) {
// no products selected: completely delete alla meta values for the post
delete_post_meta($post_id, \'products\');
} else {
$already = array();
if ( ! empty($old) ) {
foreach ($old as $value) {
if ( ! in_array($value, $new) ) {
// this value was selected, but now it isn\'t so delete it
delete_post_meta($post_id, \'products\', $value);
} else {
// this value already saved, we can skip it from saving
$already[] = $value;
}
}
}
// we don\'t save what already saved
$to_save = array_diff($new, $already);
if ( ! empty($to_save) ) {
foreach ( $to_save as $product ) {
add_post_meta( $post_id, \'products\', $product);
}
}
}