1
votes

I've added a custom field for each woocommerce product variation.

I've added a datetime input field. Then I will need to auto delete the variation when the datetime value is already past. So auto expire the woocommerce product variation.

This is my code for adding the custom input field.

// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );

// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );

//Create New fields for Variations
function variation_settings_fields( $loop, $variation_data, $variation ) {
    // Text Field
    woocommerce_wp_text_input( 
        array( 
            'id'          => '_text_field_date_expire[' . $variation->ID . ']',
            'class'       => '_text_field_date_expire',
            'type'        => 'datetime-local',  
            'label'       => __( 'Date of Expiration', 'woocommerce' ), 
            'placeholder' => '',
            'desc_tip'    => 'true',
            'description' => __( 'Expiration of Each Product Variation', 'woocommerce' ),
            'value'       => get_post_meta( $variation->ID, '_text_field_date_expire', true )
        )
    );
}


//Save New Fields for Variation
function save_variation_settings_fields( $post_id ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $post_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $post_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}

How could I get the input field value per each variations and echo it, so I could use the value for another function and delete the variations automatically?

1

1 Answers

0
votes

you can get custom woocommerce product variation field by using get_post_meta() function

echo  get_post_meta( $post->ID, '_text_field_date_expire', true );