WooCommerce 结账时的自定义隐藏字段未保存到用户元问题

Custom hidden field on WooCommerce checkout not saving to user meta issue

我不知道我在这里遗漏了什么。

我正在结帐页面上创建一个隐藏字段,其中包含客户选择后的值。

正如我在结帐页面的检查器中看到的那样,这部分正在运行。

隐藏字段应该保存给登录用户,因为我在网站的另一个地方需要它。

我有以下内容:

//This part is working!!
add_action( 'woocommerce_after_checkout_billing_form', function() {
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    foreach($items as $item => $values) {
        if( isset($values['programmakeuze']) ){
        echo '<input type="hidden" name="programchoice" id="programchoice" class="input-hidden" value="'.$values['programmakeuze'].'">';
        }
    }
});
//Save hidden field to user
function elearning_checkout_update_user_meta( $customer_id, $posted ) {
    if (!empty($_POST['programchoice'])) {
        $program = intval($_POST['programchoice'] );
        update_user_meta( $customer_id, 'programchoice', $program);
    }
}
add_action( 'woocommerce_checkout_update_user_meta', 'elearning_checkout_update_user_meta', 10, 2 );


function testing(){
 
    $id = get_current_user_id();
    $value = get_user_meta($id,'programchoice',true);
    if ( !empty($value)) {
        var_dump ($value);
        }
    }
add_action('wp_head','testing');

$value returns 没什么。我在这里错过了什么?

我已经部分重写了您的代码。包括使用woocommerce_checkout_update_customer action hook.

还要注意 for 循环中 break 的使用,因为这是关于特定 ID,因此关于 1 个唯一字段

但是,我不会使用 wp_head 操作挂钩进行调试。请参阅

但这应该足以回答您的问题:

// Display a custom hidden field after checkout billing form
function action_woocommerce_after_checkout_billing_form( $checkout ) {
    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        if ( isset( $cart_item['programmakeuze'] ) ) {
            echo '<input type="hidden" name="programchoice" id="programchoice" class="input-hidden" value="' . $cart_item['programmakeuze'] . '">';
            break;
        }
    }
}
add_action( 'woocommerce_after_checkout_billing_form', 'action_woocommerce_after_checkout_billing_form', 10, 1 );

// Save/update user data from custom field value
function action_woocommerce_checkout_update_customer( $customer, $data ) {  
    // Isset
    if ( isset( $_POST['programchoice'] ) ) {
        $customer->update_meta_data( '_programchoice', sanitize_text_field( $_POST['programchoice'] ) );
    }
}
add_action( 'woocommerce_checkout_update_customer', 'action_woocommerce_checkout_update_customer', 10, 2 );

// Debugging purposes
function action_wp_head(){
    // Get user id
    $user_id = get_current_user_id();
    
    // Get user meta
    $value = get_user_meta( $user_id, '_programchoice', true );

    // NOT empty
    if ( ! empty( $value ) ) {
        var_dump ( $value );
    }
}
add_action( 'wp_head', 'action_wp_head' );