繁体   English   中英

在购物车中设置自定义字段值,并将其另存为Woocommerce 3中的订单商品数据

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

在wooCommerce插件中,我想发送$ item ['_ custom_sizer']此值以检出页面和电子邮件模板,但我无法传递该值。 请帮帮我。

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 );

已更新 …请尝试以下操作:

// 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'] );
}

代码进入您的活动子主题(或活动主题)的function.php文件中。 经过测试和工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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