php 使用自定义信息和价格将产品添加到购物车

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31482540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:27:55  来源:igfitidea点击:

Adding a product to cart with custom info and price

phpwordpresswoocommerce

提问by Kevin S

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

我已经安装了 woocommerce 来处理 wordpress 商店的产品输入和结帐过程。

The shop page is custom built which allows the user to pick a product from a list and customise it which outputs a price in javascript based on information stored in the database.

商店页面是自定义构建的,它允许用户从列表中选择产品并自定义它,该页面基于存储在数据库中的信息以 javascript 输出价格。

The products stored in the db are valued at 0.00 because they're different prices depending on the variables chosen.

存储在 db 中的产品的价值为 0.00,因为它们的价格取决于选择的变量。

The output data I'm ready to pass to woocommerce is as follows:

我准备传递给woocommerce的输出数据如下:

  • WC Product ID (This matches a product in the db)
  • Custom Price
  • Custom Image
  • Custom Description (e.g. 100mm x 100mm)
  • Build Data (to be stored against the item but not seen in checkout)
  • WC 产品 ID(这与数据库中的产品匹配)
  • 定制价格
  • 自定义图片
  • 自定义描述(例如 100mm x 100mm)
  • 构建数据(针对项目存储但在结账时看不到)

I'm trying to find a way to add a product to the cart using the product ID (to make it valid) and then overriding the price with the custom price and attaching meta data which most will be seen at checkout and one will be hidden until seen in the wordpress admin.

我正在尝试找到一种使用产品 ID(使其有效)将产品添加到购物车的方法,然后使用自定义价格覆盖价格并附加元数据,这些数据将在结账时看到,一个将被隐藏直到在 wordpress 管理员中看到。

Adding the product to the cart is achieved by using:

将产品添加到购物车是通过使用以下方法实现的:

$woocommerce->cart->add_to_cart($_POST['custom_product_id']);

After which point I'm finding it impossible to override the price and add additional information.

在那之后,我发现无法覆盖价格并添加其他信息。

回答by Kevin S

All of this code goes into functions.php

所有这些代码都进入了functions.php

  1. This captures additional posted information (all sent in one array)

    add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
    function wdm_add_item_data($cart_item_data, $product_id) {
    
        global $woocommerce;
        $new_value = array();
        $new_value['_custom_options'] = $_POST['custom_options'];
    
        if(empty($cart_item_data)) {
            return $new_value;
        } else {
            return array_merge($cart_item_data, $new_value);
        }
    }
    
  2. This captures the information from the previous function and attaches it to the item.

    add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
    function wdm_get_cart_items_from_session($item,$values,$key) {
    
        if (array_key_exists( '_custom_options', $values ) ) {
            $item['_custom_options'] = $values['_custom_options'];
        }
    
        return $item;
    }
    
  3. This displays extra information on basket & checkout from within the added info that was attached to the item.

    add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
    function add_usr_custom_session($product_name, $values, $cart_item_key ) {
    
        $return_string = $product_name . "<br />" . $values['_custom_options']['description'];// . "<br />" . print_r($values['_custom_options']);
        return $return_string;
    
    }
    
  4. This adds the information as meta data so that it can be seen as part of the order (to hide any meta data from the customer just start it with an underscore)

    add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
    function wdm_add_values_to_order_item_meta($item_id, $values) {
        global $woocommerce,$wpdb;
    
        wc_add_order_item_meta($item_id,'item_details',$values['_custom_options']['description']);
        wc_add_order_item_meta($item_id,'customer_image',$values['_custom_options']['another_example_field']);
        wc_add_order_item_meta($item_id,'_hidden_field',$values['_custom_options']['hidden_info']);
    
    }
    
  5. If you want to override the price you can use information saved against the product to do so

    add_action( 'woocommerce_before_calculate_totals', 'update_custom_price', 1, 1 );
    function update_custom_price( $cart_object ) {
        foreach ( $cart_object->cart_contents as $cart_item_key => $value ) {       
            // Version 2.x
            //$value['data']->price = $value['_custom_options']['custom_price'];
            // Version 3.x / 4.x
            $value['data']->set_price($value['_custom_options']['custom_price']);
        }
    }
    
  1. 这会捕获其他发布的信息(全部以一个数组发送)

    add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
    function wdm_add_item_data($cart_item_data, $product_id) {
    
        global $woocommerce;
        $new_value = array();
        $new_value['_custom_options'] = $_POST['custom_options'];
    
        if(empty($cart_item_data)) {
            return $new_value;
        } else {
            return array_merge($cart_item_data, $new_value);
        }
    }
    
  2. 这会捕获来自前一个函数的信息并将其附加到项目。

    add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
    function wdm_get_cart_items_from_session($item,$values,$key) {
    
        if (array_key_exists( '_custom_options', $values ) ) {
            $item['_custom_options'] = $values['_custom_options'];
        }
    
        return $item;
    }
    
  3. 这会显示附加到商品的附加信息中有关购物篮和结帐的额外信息。

    add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
    function add_usr_custom_session($product_name, $values, $cart_item_key ) {
    
        $return_string = $product_name . "<br />" . $values['_custom_options']['description'];// . "<br />" . print_r($values['_custom_options']);
        return $return_string;
    
    }
    
  4. 这会将信息添加为元数据,以便将其视为订单的一部分(要向客户隐藏任何元数据,只需以下划线开头即可)

    add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
    function wdm_add_values_to_order_item_meta($item_id, $values) {
        global $woocommerce,$wpdb;
    
        wc_add_order_item_meta($item_id,'item_details',$values['_custom_options']['description']);
        wc_add_order_item_meta($item_id,'customer_image',$values['_custom_options']['another_example_field']);
        wc_add_order_item_meta($item_id,'_hidden_field',$values['_custom_options']['hidden_info']);
    
    }
    
  5. 如果您想覆盖价格,您可以使用针对产品保存的信息来执行此操作

    add_action( 'woocommerce_before_calculate_totals', 'update_custom_price', 1, 1 );
    function update_custom_price( $cart_object ) {
        foreach ( $cart_object->cart_contents as $cart_item_key => $value ) {       
            // Version 2.x
            //$value['data']->price = $value['_custom_options']['custom_price'];
            // Version 3.x / 4.x
            $value['data']->set_price($value['_custom_options']['custom_price']);
        }
    }
    

All your custom information will appear in the customer email and order from within wordpress providing you added it as meta data (4.)

您的所有自定义信息都将出现在客户电子邮件中,并从 wordpress 中订购,前提是您将其添加为元数据 (4.)

回答by Krishna Gupta

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

第 1 步:- 您需要创建一些自定义隐藏字段以发送将显示在单个产品页面上的自定义数据。例如 :-

add_action('woocommerce_before_add_to_cart_button', 'custom_data_hidden_fields');
function custom_data_hidden_fields() {
    echo '<div class="imput_fields custom-imput-fields">
        <label class="price_prod">price: <br><input type="text" id="price_prod" name="price_prod" value="" /></label>
        <label class="quantity_prod">quantity: <br>
            <select name="quantity_prod" id="quantity_prod">
                <option value="1" selected="selected">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
            </select>
        </label>
    </div><br>';
}

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.

第 2 步:- 现在完成后,您需要编写将所有产品自定义字段保存到购物车项目数据的主要逻辑,请按照以下代码操作。

// 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.

第 3 步:您需要使用自定义计算覆盖商品价格。它将适用于您的单个产品会话的每个场景。

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

一切都将在functions.php中完成

Reference Site

参考网站