将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上 [英] Save product custom field radio button value in cart and display it on Cart page

查看:59
本文介绍了将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主题主题的functions.php上使用以下代码在woocommerce单一产品页面上添加了一些自定义选项:

I have added some custom options on woocommerce single product page using the code below on my theme's 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");

现在,我想在购物车页面上显示所选的选项值。请帮我做到这一点。
谢谢

Now i want to display the selected option value on cart page. Please help me to do this. Thanks

推荐答案

以下是将产品自定义字段存储在购物车对象中并在购物车和结帐中显示的完整代码页面:

Here is the complete code to Store product custom field in cart object and display that in Cart and Checkout pages:

// 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' ] = $_REQUEST['custom_field'];
        // below statement make sure every add to cart action as unique line item
        $cart_item_data['unique_key'] = md5( microtime().rand() );
        WC()->session->set( 'my_order_data', $_REQUEST['custom_field'] );
    }
    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( !empty( $cart_data ) )
        $custom_items = $cart_data;

    if( isset( $cart_item['custom_field'] ) ) {
        $custom_items[] = array(
            'key'       => __('Custom Item', 'woocommerce'),
            'value'     => $cart_item['custom_field'],
            'display'   => $cart_item['custom_field'],
        );
    }
    return $custom_items;
}

代码包含在您活动的子主题的function.php文件中(

此代码已经过测试并且可以正常工作。

This code is tested and works.

这篇关于将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆