Mohit Chandel
Mohit Chandel

Reputation: 1916

Custom WooCommerce product fields not saving in database

I made a custom field for a WooCommerce product but when I am trying to save it, Its value is not saving in the database

function product_certification_number() {
    $args = array(
        'id'            => 'product_certification_number',
        'label'         => sanitize_text_field( 'Product Certification Number' ),
    );
    woocommerce_wp_text_input( $args );
}
add_action('woocommerce_product_options_general_product_data','product_certification_number' );

function product_certification_number_save( $post_id ) {

    if ( ! ( isset( $_POST['woocommerce_meta_nonce'], $_POST[ 'product_certification_number' ] ) || wp_verify_nonce( sanitize_key( $_POST['woocommerce_meta_nonce'] ), 'woocommerce_save_data' ) ) ) {
        return false;
    }

    $product_teaser = sanitize_text_field(
        wp_unslash( $_POST[ 'product_certification_number' ] )
    );

    update_post_meta(
        $post_id,
        'product_certification_number',
        esc_attr( $product_teaser )
    );
}
add_action('woocommerce_process_product_meta','product_certification_number_save');

Upvotes: 1

Views: 1761

Answers (2)

glinda93
glinda93

Reputation: 8489

I've wasted my two hours in this problem.

I finally found out that you need to call save_meta_data after update_meta_data:

/** @var WC_Product */
$product->update_meta_data($key, $value);
$product->save_meta_data();

Upvotes: 2

7uc1f3r
7uc1f3r

Reputation: 29650

EDIT: used woocommerce_admin_process_product_object to save instead of outdated woocommerce_process_product_meta. Thnx to: @LoicTheAztec


// Add field
function product_certification_number() {
    $args = array(
        'id'            => '_product_certification_number',
        'label'         => __( 'Product Certification Number', 'woocommerce' ),
        'class'         => 'custom-field',
        'desc_tip'      => true,
        'description'   => __( 'My description', 'woocommerce' ),   
    );
    woocommerce_wp_text_input( $args );
}
add_action('woocommerce_product_options_general_product_data','product_certification_number', 10, 0 );

// Save
function product_certification_number_save( $product ){
    if( isset($_POST['_product_certification_number']) ) {
        $product->update_meta_data( '_product_certification_number', sanitize_text_field( $_POST['_product_certification_number'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'product_certification_number_save', 10, 1 );

Upvotes: 3

Related Questions