簡體   English   中英

將產品自定義字段值保存在購物車中並將其顯示在購物車和結帳中

[英]Save product custom field value in cart and display it on Cart and checkout

我在 woocommerce 單一產品頁面上添加了一些自定義選項,使用主題的functions.php 上的以下代碼:

     function options_on_single_product(){
     ?>
      <input type="radio" name="option1" checked="checked" value="option1"> option 1 <br />
      <input type="radio" name="option1" value="option2"> option 2
       <?php
      }
       add_action("woocommerce_before_add_to_cart_button", "options_on_single_product");

現在我想在購物車頁面上顯示選定的選項值。 請幫我做這件事。 謝謝

這是在購物車對象中存儲產品自定義字段並在購物車和結帳頁面中顯示的完整代碼:

// Output the Custom field in Product pages
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product", 1);
function options_on_single_product(){
    ?>
        <label for="custom_field">
            <input type="radio" name="custom_field" checked="checked" value="option1"> option 1 <br />
            <input type="radio" name="custom_field" value="option2"> option 2
        </label> <br />
    <?php
}

// Stores the custom field value in Cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_field_data', 10, 2 );
function save_custom_product_field_data( $cart_item_data, $product_id ) {
    if( isset( $_REQUEST['custom_field'] ) ) {
        $cart_item_data[ 'custom_field' ] = esc_attr($_REQUEST['custom_field']);
        // below statement make sure every add to cart action as unique line item
        $cart_item_data['unique_key'] = md5( microtime().rand() );
    }
    return $cart_item_data;
}

// Outuput custom Item value in Cart and Checkout pages
add_filter( 'woocommerce_get_item_data', 'output_custom_product_field_data', 10, 2 );
function output_custom_product_field_data( $cart_data, $cart_item ) {
    if( isset( $cart_item['custom_field'] ) ) {
        $cart_data[] = array(
            'key'       => __('Custom Item', 'woocommerce'),
            'value'     => $cart_item['custom_field'],
            'display'   => $cart_item['custom_field'],
        );
    }
    return $cart_data;
}

代碼位於活動子主題(或主題)的 function.php 文件或任何插件文件中。

此代碼經過測試並有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM