PHP   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

我在主题主题的functions.PHP中使用以下代码在woocommerce单一产品页面添加了一些@L_618_6@选项:

     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' ] = $_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文件中,或者在任何插件文件中.

代码已经过测试并且可以工作.

大佬总结

以上是大佬教程为你收集整理的php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上全部内容,希望文章能够帮你解决php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: