WooCommerce:将输入添加到购物车,然后将数据添加到购物车项目

WooCommerce: Add input to cart and then add the data to cart item

我一直在尝试为购物车中的商品添加一个选项,以便客户可以重命名产品。这用于他们跟踪要发送给不同人的同一类型的不同产品(制作礼篮系统)

我已经使用 woocommerce_cart_item_name 过滤器将输入字段添加到购物车商品中。我正在使用 this link 的答案并在用户单击输入框旁边的 "ADD" 按钮时触发 javascript 中的 wc_update_cart,但似乎没有工作。

有没有其他方法可以在添加产品后将此自定义名称数据添加到相应的购物车项目中?我知道我可以在将它添加到购物车时执行此操作(或者解决方法是删除该产品并将其重新添加到这个新字段中。但我不想那样做)

在此先感谢您的帮助。

找到问题了。

我在输入框旁边的 "Add" 按钮,我用来触发 wc_update_cart 就像 jQuery(document).trigger('wc_update_cart'); 没有验证我在 php端为$_POST['update_cart']的值。当我意识到我将 woocommerce_cart_item_name 过滤器更改为仅添加输入框并使用 Update Basket 按钮更新名称时。所以我的代码改为:

<?php
    add_filter('woocommerce_cart_item_name','custom_naming_front',10,3);

    function custom_naming_front($product_title,$cart_item,$cart_item_key){
        if(isset($cart_item['custom_name']) && !empty($cart_item['custom_name'])){
            $product_title=$cart_item['custom_name'];
        }
        $product_title .= '<div class="custom-name-form-wrapper" id="custom-name'.$cart_item_key.'">
                                    <input type="text" name="cart['.$cart_item_key.'][custom_name]" id="custom_name_text'.$cart_item_key.'" value="" placeholder="enter the name you want to give this product" />
                                </div>
                            </div>';

        return $product_title;

    }
?>

显示更新名称的函数如下所示:

<?php

    function custom_name_save_to_cart(){
        if ( ( ! empty( $_POST['apply_coupon'] ) || ! empty( $_POST['update_cart'] ) || ! empty( $_POST['proceed'] ) ) && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( $_POST['_wpnonce'], 'woocommerce-cart' ) ) {
                $cart_totals  = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
            if ( ! WC()->cart->is_empty()) {
                foreach ( WC()->cart->cart_contents as $cart_item_key => $values ) {
                    if ( ! isset( $cart_totals[ $cart_item_key ] ) || ! isset( $cart_totals[ $cart_item_key ]['custom_name'] ) ) {
                        continue;
                    }
                    WC()->cart->cart_contents[ $cart_item_key ]['custom_name'] = $cart_totals[ $cart_item_key ]['custom_name'];

                }
            }

        }

     }
    add_action( 'wp_loaded', 'custom_name_save_to_cart', 25);
?>