Add, update or remove product custom field in WooCommerce

Tags: , , , ,



I use the following lines to save a Value to the database. 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.

Answer

Try instead the following revisited code using WC_Data delete_meta_data() method to remove product meta data (meta key + value):

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



Source: stackoverflow