Add custom Product data dynamically as item meta data on the Order

后端 未结 2 1673
星月不相逢
星月不相逢 2020-12-20 00:02

Is it possible to add a metadata on a product which is inside the Order?

In this case, there would be one metadata but each product (in the order) would have differe

2条回答
  •  我在风中等你
    2020-12-20 00:20

    After creating attribute "The Meta" and adding it to the product.

    I answered my problem with the following:

    First: Add the meta via woocommerce_add_cart_item_data filter hook. This would add first the meta to the items inside the cart.

    function add_cart_item_data( $cart_item_data, $product_id ) {
        $cart_item_data[ "meta1" ] = $_POST["meta1"];  
        $cart_item_data[ "meta2"] = $_POST["meta2"]; 
        return $cart_item_data;
    }
    add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 2 );
    

    Second: Save the meta added to the cart to the actual items purchased within the order

    function adding_custom_data_in_order_items_meta( $item_id, $values, $cart_item_key ) {
        if ( isset($values['meta1']) && isset($values['meta2']) ) {
            $the_meta = $values['meta1'] . '.' .  $values['meta2'];
            wc_add_order_item_meta($item_id, 'pa-the-meta', $the_meta );
        }
    }
    add_action('woocommerce_add_order_item_meta','adding_custom_data_in_order_items_meta', 10, 3 );
    

提交回复
热议问题