Adding a product to cart with custom info and price

前端 未结 2 1504
谎友^
谎友^ 2020-12-08 01:13

I have installed woocommerce to handle product input & checkout process of a wordpress shop.

The shop page is custom built which allows the user to pick a produc

2条回答
  •  抹茶落季
    2020-12-08 01:49

    Step 1:- You need to create some custom hidden fields to send custom data that will show on single product page. for example :-

    add_action('woocommerce_before_add_to_cart_button', 'custom_data_hidden_fields');
    function custom_data_hidden_fields() {
        echo '

    '; }

    Step 2:- Now after done that you need to write the main logic for Save all Products custom fields to your cart item data, follow the below codes.

    // Logic to Save products custom fields values into the cart item data
    add_action( 'woocommerce_add_cart_item_data', 'save_custom_data_hidden_fields', 10, 2 );
    function save_custom_data_hidden_fields( $cart_item_data, $product_id ) {
    
        $data = array();
    
        if( isset( $_REQUEST['price_prod'] ) ) {
            $cart_item_data['custom_data']['price_pro'] = $_REQUEST['price_prod'];
            $data['price_pro'] = $_REQUEST['price_prod'];
        }
    
        if( isset( $_REQUEST['quantity_prod'] ) ) {
            $cart_item_data['custom_data']['quantity'] = $_REQUEST['quantity_prod'];
            $data['quantity'] = $_REQUEST['quantity_prod'];
        }
    
        // below statement make sure every add to cart action as unique line item
        $cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
        WC()->session->set( 'price_calculation', $data );
    
        return $cart_item_data;
    }
    

    Step 3: you need to override the item price with your custom calculation. It will work with your every scenario of your single product sessions.

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 10 );
    function add_custom_item_price( $cart_object ) {
    
        foreach ( $cart_object->get_cart() as $item_values ) {
    
            ##  Get cart item data
            $item_id = $item_values['data']->id; // Product ID
            $original_price = $item_values['data']->price; // Product original price
    
            ## Get your custom fields values
            $price1 = $item_values['custom_data']['price1'];
            $quantity = $item_values['custom_data']['quantity'];
    
            // CALCULATION FOR EACH ITEM:
            ## Make HERE your own calculation 
            $new_price = $price1 ;
    
            ## Set the new item price in cart
            $item_values['data']->set_price($new_price);
        }
    }
    

    Everything will be done inside the functions.php

    Reference Site

提交回复
热议问题