Woocommerce add custom checkbox field in cart item and save it in order

Viewed 674

my project is..

I want to add a checkbox ONLY in every cart item in cart page (NOT in single product page like add_before_add_to cart_button), so that the customer can select if the product is for gift..like the photo

cart item in cart page

..and also display the value in checkout page and in order details...

after a lot of searches i do something like this...but only display the checkboxes in cart item..not save..not displayed in order...

where am i wrong?? Can you help me?

 * Add a text field to each cart item
 */
function prefix_after_cart_item_name( $cart_item, $cart_item_key ) 
{

 ?>
            <div class="simple-selects">
                <div class="col-md-6">
                    <p><input type="checkbox" name="gift" id="gift"><?php _e( " Wrap as Gift", "aoim");?></p>
                </div>
            </div>  <?php
 
}
add_action( 'woocommerce_after_cart_item_name', 'prefix_after_cart_item_name', 10, 2 );


/**
         * Add data to cart item
         */
        add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 2 );
        function add_cart_item_data( $cart_item_data, $product_id ) {

            if ( isset( $_POST ['gift'] )) {
                /*$custom_data  = array() ;
                $custom_data [ 'gift' ]    = isset( $_POST ['gift'] ) ?  sanitize_text_field ( $_POST ['gift'] ) : "" ;
                $cart_item_meta ['custom_data']     = $custom_data ;*/
                $cart_item_data[ 'gift' ] = sanitize_text_field($_POST['gift']);

            }

            return $cart_item_data;
        }
add_action( 'woocommerce_checkout_update_order_meta', 'save_idvopros_as_order_meta', 10, 3 );
function save_idvopros_as_order_meta( $order_id, $data ) {
    foreach(WC()->cart->get_cart() as $cart_item)
        $gift = empty($cart_item['gift']) ? 'yes' : $cart_item['gift'];
    update_post_meta($order_id, '_idvopros_temp', $gift, true);
}
add_action('woocommerce_order_status_completed', 'ustanovka_oplaty');
function ustanovka_oplaty( $order_id) {

    $gift = get_post_meta( $order_id, '_idvopros_temp', true );
    if ( ! empty( $gift ) ) {
        update_post_meta($order_id, 'wpcf-idvopros', $gift );
        delete_post_meta($order_id, '_idvopros_temp' );
    }
}
0 Answers
Related