Display and save added custom cart item data on Woocommerce Cart, Checkout and Orders

前端 未结 3 702
北恋
北恋 2021-01-22 04:51

I am trying to add product in cart with cart item meta data. Here is the code :

$cart_item_data = array();

$cart_item_data[\'add_size\'] = array(\'PR CODE\'=>         


        
相关标签:
3条回答
  • 2021-01-22 05:03

    You can add the product to the cart using the following code:

    WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
    

    Reference : https://docs.woocommerce.com/wc-apidocs/source-class-WC_AJAX.html#356-397

    Have a look at this too: add meta to a product on cart WooCommerce

    0 讨论(0)
  • 2021-01-22 05:03

    After I spent the last hours figuring things out I found out that the method has actually changed a bit over the time.

    Method:

    $woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
    

    In my case I needed to do this and the custom meta data got automatically displayed in the cart and order:

    $woocommerce->cart->add_to_cart($product_id, $quantity, NULL, NULL, array('your_key' => 'your_value'));
    

    You can find out more here: https://woocommerce.wp-a2z.org/oik_api/wc_cartadd_to_cart/

    0 讨论(0)
  • 2021-01-22 05:09

    To display and save custom meta data added to cart in cart, checkout and orders when using:

    WC()->cart->add_to_cart( $product_id ,1,  0,array(), array('add_size' => array('PR CODE'=>'1.0') );
    

    You will use the following code:

    // Display custom cart item meta data (in cart and checkout)
    add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 );
    function display_cart_item_custom_meta_data( $item_data, $cart_item ) {
        $meta_key = 'PR CODE';
        if ( isset($cart_item['add_size']) && isset($cart_item['add_size'][$meta_key]) ) {
            $item_data[] = array(
                'key'       => $meta_key,
                'value'     => $cart_item['add_size'][$meta_key],
            );
        }
        return $item_data;
    }
    
    // Save cart item custom meta as order item meta data and display it everywhere on orders and email notifications.
    add_action( 'woocommerce_checkout_create_order_line_item', 'save_cart_item_custom_meta_as_order_item_meta', 10, 4 );
    function save_cart_item_custom_meta_as_order_item_meta( $item, $cart_item_key, $values, $order ) {
        $meta_key = 'PR CODE';
        if ( isset($values['add_size']) && isset($values['add_size'][$meta_key]) ) {
            $item->update_meta_data( $meta_key, $values['add_size'][$meta_key] );
        }
    }
    

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

    Example display on Cart (and Checkout) pages:

    Example display on Orders (and email notifications):

    0 讨论(0)
提交回复
热议问题