在添加到购物车时,通过Woocommerce中的GET请求将自定义数据传递到购物车项目

在添加到购物车时,通过Woocommerce中的GET请求将自定义数据传递到购物车项目

问题描述:

How to pass custom meta data to cart item via parameters in the URL (using a GET request) when adding to cart a product?

Example:

  • custom_price = 99.99
  • custom_reference_meta = REF0019

So the Add to cart URL will be something like:
http://yourdomain.com/?add-to-cart=25&custom_price=99.99&custom_reference_meta=REF0019

I need to do this because I'm doing a adding product via query string.

This can be done easily with a custom function hooked in woocommerce_add_cart_item_data filter hook, that will store your custom data in cart item, once product is added to cart via a GET request.

Optionally you can use a 2nd hooked function to display that data on cart and checkout. This will also allow you to check that the data is correctly set in cart item.

The code:

// Set custom data as custom cart data in the cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_data_in_cart_object', 30, 3 );
function save_custom_data_in_cart_object( $cart_item_data, $product_id, $variation_id ) {
    if( ! isset($_GET['custom_price']) || ! isset($_GET['custom_reference_meta']) )
        return $cart_item_data; // Exit

    // Get the data from the GET request
    $custom_price          = esc_attr( $_GET['custom_price'] );
    $custom_reference_meta = esc_attr( $_GET['custom_reference_meta'] );

    // Set the data as custom cart data for the cart item
    $cart_item_data['custom_data']['custom_price'] = esc_attr( $_GET['custom_price'] );
    $cart_item_data['custom_data']['custom_reference_meta'] = esc_attr( $_GET['custom_reference_meta'] );

    return $cart_item_data;
}

// Optionally display Custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'custom_data_on_cart_and_checkout', 99, 2 );
function custom_data_on_cart_and_checkout( $cart_data, $cart_item = null ) {

    if( isset( $cart_item['custom_data']['custom_price'] ) )
        $cart_data[] = array(
            'name' => 'Custom price',
            'value' => $cart_item['custom_data']['custom_price']
        );

    if( isset( $cart_item['custom_data']['custom_reference_meta'] ) )
        $cart_data[] = array(
            'name' => 'Custom reference',
            'value' => $cart_item['custom_data']['custom_reference_meta']
        );

    return $cart_data;
}

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

enter image description here