简体   繁体   中英

Set a custom field value in cart and save it as order item data in Woocommerce 3

In wooCommerce plugin I want to send $item['_custom_sizer'] this value to check out page and email template but i am not able to pass the value. please help me out.

add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_custom_data_vase', 10, 2 );
function add_cart_item_custom_data_vase( $cart_item_meta, $product_id ) {
  global $woocommerce;
    $new_value = array();
    $new_value['_custom_sizer'] = $_POST['sizer'];

    if(empty($cart_item_data)) {
        return $new_value;
    } else {
        return array_merge($cart_item_data, $new_value);
    } 
}

//Get it from the session and add it to the cart variable
function get_cart_items_from_session( $item, $values, $key ) {

    if (array_key_exists( '_custom_sizer', $values ) ) {
        $item['_custom_sizer'] = $values['_custom_sizer'];
    }

    return $item;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'get_cart_items_from_session', 1, 3 );

Updated … Try the following instead:

// Add "Sizer" as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_custom_data', 20, 2 );
function add_cart_item_custom_data( $cart_item_data, $product_id ) {
    if( isset($_POST['sizer']) && ! empty($_POST['sizer']) ){
        $cart_item_data['custom_sizer'] = sanitize_text_field( $_POST['sizer'] );
    }
    return $cart_item_data;
}


// Display "Sizer" in cart and checkout
add_filter( 'woocommerce_get_item_data', 'display_sizer_in_cart_checkout', 20, 2 );
function display_sizer_in_cart_checkout( $cart_item_data, $cart_item ) {
    if( isset($cart_item['custom_sizer']) ){
        $cart_item_data[] = array(
            'name' => __('Metal Type'),
            'value' => $cart_item['custom_sizer'],
        );
    }
    return $cart_item_data;
}

// Save "sizer" as custom order item meta data
add_action( 'woocommerce_checkout_create_order_line_item', 'update_order_item_meta', 20, 4 );
function update_order_item_meta( $item, $cart_item_key, $values, $order ) {
    if( isset($values['custom_sizer']) )
        $item->update_meta_data( 'Sizer', $values['custom_sizer'] );
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM