How to get Woocommerce Variation ID?

后端 未结 2 580
暗喜
暗喜 2020-12-11 07:06

I\'ve already had this code on functions.php

This code is to add a new field on each product variation to have datetime input field, so variations would automaticall

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 07:43

    In WooCommerce 3+, it's $variation->get_id() from $variation function argument, which is an instance of the WC_Product_Variation.

    The method get_id() is inherited from WC_Data class.

    So in your code it should be instead:

    'id' => '_text_field_date_expire[' . $variation->get_id() . ']',
    

    Since WooCommerce 3, All WC_Product properties can't be accessed directly. Instead, you need to use the available methods.


    Also in your hooked function save_variation_settings_fields() you are declaring 2 arguments, so there is one missing. It should be:

    //Save New Fields for Variation// Save Variation Settings
    add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
    
    function save_variation_settings_fields( $variation_id, $i ) {
        // Text Field
        $text_field = $_POST['_text_field_date_expire'][ $variation_id ];
        if( ! empty( $text_field ) ) {
            update_post_meta( $variation_id, '_text_field_date_expire', esc_attr( $text_field ) );
        }
    }
    

    See the source code for woocommerce_save_product_variation action hook

提交回复
热议问题