Php 在WooCommerce中添加、更新或删除产品自定义字段

Php 在WooCommerce中添加、更新或删除产品自定义字段,php,wordpress,woocommerce,product,custom-fields,Php,Wordpress,Woocommerce,Product,Custom Fields,我使用以下行将值保存到数据库中。我有一个关于这个代码的问题,当我删除输入时,它仍然保留它。删除的唯一方法是将(空格)作为输入 $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_prod

我使用以下行将
保存到数据库中。我有一个关于这个代码的问题,当我删除输入时,它仍然保留它。删除的唯一方法是将
(空格)作为输入

$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\u Data
delete\u meta\u Data()
方法删除产品元数据(meta key+value),尝试以下重新访问的代码:


它应该可以工作。

使用
WC\u Data
delete\u meta\u Data()
方法来删除产品元数据(meta键+值),尝试以下重新访问的代码:

它应该会起作用

$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   
}