在 WooCommerce 订单中添加到购物车自定义字段数据

Get added to cart custom field data in WooCommerce order

在 WooCommerce 中,我在将产品添加到 cookie 中的购物车时设置自定义字段:

add_action( 'init', 'wpcd_set_cookie', 1 );
function wpcd_set_cookie() {
    if(isset( $_POST[ 'idp' ] ) ) :
        $cookie_value = sanitize_text_field( $_POST[ 'idp' ] );
        setcookie( 'idp', $cookie_value, time() + (86400 * 999), '/' ); // 86400 = 1 day            
        header("Refresh:0");            
    endif;
}

cookie 已正确设置,但我无法在此挂钩中获取其值:

add_action('woocommerce_order_status_completed', 'ustanovka_oplaty');
function ustanovka_oplaty( $order_id) {

    $idp = isset( $_COOKIE['idp'] ) ? $_COOKIE['idp'] : 'not set';

    // this $idp = 'not set ' why?  

    add_post_meta($order_id, 'wpcf-idvopros', $idp, true);
}

为什么?

我该如何解决这个问题?


编辑 - 我的表单将产品添加到购物车:

<form action="<?php the_permalink(); ?>" id="PaySumForm" method="post">

    <input type="hidden"  name="idp" id="idp" value="<?php echo $post->ID; ?>" class="required requiredField " />

    <button type="contsubmit" class="payb qbutton">buy</button>

</form>

Answering the why:

It's is because a cookie is set on client side (in customer browser). The woocommerce_order_status_completed is a backend Woocommerce process and can't access that cookie data.

现在您应该忘记 cookies 并使用以下代码:

1) 将您的 "idp" 自定义字段值保存在购物车商品中

add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_field_in_cart', 10, 2 );
function save_custom_product_field_in_cart( $cart_item_data, $product_id ) {
    if( isset( $_POST['idp'] ) )
        $cart_item_data[ 'idp' ] = sanitize_text_field($_POST['idp']);

    return $cart_item_data;
}

2) 在订单元数据中保存 "idp" 自定义字段值(临时):

add_action( 'woocommerce_checkout_update_order_meta', 'save_idvopros_as_order_meta', 10, 3 );
function save_idvopros_as_order_meta( $order_id, $data ) {
    foreach(WC()->cart->get_cart() as $cart_item)
        $idp = empty($cart_item['idp']) ? 'no' : $cart_item['idp'];
    update_post_meta($order_id, '_idvopros_temp', $idp, true);
}

3) 最后,重新访问函数:

add_action('woocommerce_order_status_completed', 'ustanovka_oplaty');
function ustanovka_oplaty( $order_id) {

    $idp = get_post_meta( $order_id, '_idvopros_temp', true );
    if ( ! empty( $idp ) ) {
        update_post_meta($order_id, 'wpcf-idvopros', $idp );
        delete_post_meta($order_id, '_idvopros_temp' );
    }
}

这应该有效