php - 在 WooCommerce 中添加、更新或删除产品自定义字段
问题描述
我使用以下几行将 a 保存Value
到数据库中。我对这段代码有一个问题,当我删除输入时它仍然保留它。删除它的唯一方法是将
(空格)作为输入。
$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' );
}
请给我任何您认为可以解决此问题的提示。
解决方案
尝试使用以下重新访问的代码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
}
它应该工作。
推荐阅读
- java - 有没有办法模拟 Socket 和 Connection 超时?
- python - 谷歌应用引擎中的 Flask-Compress 模块未压缩响应正文
- html - 为什么`display:none`不加载背景图片?
- r - 如何编写一个函数来对多个数据集应用分析并将结果合并到一个数据框中?
- ios - 自定义流程中的 Docusign iOS SDK 集成问题(在集成自己的后端和 docusign iOS SDK 时)
- kubernetes - 无法通过内部端点调用 Kubernetes 服务
- xml - 如何获取 XML 的索引?(仅限 XPath)
- netsuite - NetSuite SuiteScript 2.0 如何解析suitescript中的内容文本
- mysql - SQL查询查找每本书的最后一个问题/返回记录的状态
- ios - 找不到模块“至少节点”