duanri1985 2018-08-04 12:57
浏览 121

在购物车中设置自定义字段值,并将其保存为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 );
  • 写回答

1条回答 默认 最新

  • ds42774 2018-08-05 06:34
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题