[英]Add, update or remove product custom field in WooCommerce
I use the following lines to save a Value
to the database.我使用以下几行将
Value
保存到数据库中。 I have one question regarding this code, when I delete input it still keeps it.我对这段代码有一个问题,当我删除输入时它仍然保留它。 The only way to delete that is to put
删除它的唯一方法是放
(space) as input. (空格)作为输入。
$field_key_pills_1 = 'custom_text_field_category_pills';
if ( isset( $_POST[$field_key_pills_1] ) && ! empty( $_POST[$field_key_pills_1] ) ) {
$attribute_pills_1 = wc_get_product( $post_id );
$attribute_pills_1->update_meta_data( $field_key_pills_1, sanitize_text_field( $_POST[$field_key_pills_1] ) );
$attribute_pills_1->save();
} else {
$attribute_pills_1 = wc_get_product( $post_id );
$attribute_pills_1 = delete_post_meta( $post_id, 'custom_text_field_category_pills' );
}
Please give me any tip that you think, can solve this problem.请给我任何您认为可以解决此问题的提示。
Try instead the following revisited code using WC_Data
delete_meta_data()
method to remove product meta data (meta key + value):请尝试使用
WC_Data
delete_meta_data()
方法删除产品元数据(元键 + 值)来重新访问以下代码:
$key_pills_1 = 'custom_text_field_category_pills';
$product_pills1 = wc_get_product( $post_id );
// Check that the product and the product input field exists
if ( is_a($product_pills1, 'WC_Product') && isset($_POST[$key_pills_1]) {
if ( ! empty($_POST[$key_pills_1]) ) {
$product_pills1->update_meta_data( $key_pills_1, sanitize_text_field($_POST[$key_pills_1]) ); // Set or update
} else {
$product_pills1->delete_meta_data( $key_pills_1 ); // remove
}
$product_pills1->save(); // Sync and save to database
}
It should work.它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.