将WooCommerce结账自定义字段保存为用户元数据。

3

我希望将自定义注册字段添加到我的结算页面表单中。

我正在使用此代码将自定义字段添加到我的注册区域。

顺便说一下,我正在使用我的结算字段来作为我的注册字段。

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {

    $fields['billing']['shipping_tc'] = array(
        'label' => __('TC Kimlik No', 'woocommerce'),
        'placeholder' => _x('Fatura İçin Gerekli', 'placeholder', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-wide'),
        'clear' => true
    );
    
    return $fields;
}

我尝试使用此代码更新用户元数据

add_action( 'woocommerce_checkout_update_user_meta', 'reigel_woocommerce_checkout_update_user_meta', 10, 2 );
function reigel_woocommerce_checkout_update_user_meta( $customer_id, $posted ) {
    if (isset($posted['shipping_tc'])) {
        $dob = sanitize_text_field( $posted['shipping_tc'] );
        update_user_meta( $user_id, $dob, $_POST[$dob]);
    }
}

没有错误但它不起作用...有人能帮帮我吗? 我使用下面的代码成功地更新了其他默认结账数值;
// Custom function to save Usermeta or Billing Address of registered user
add_action('woocommerce_created_customer','zk_save_billing_address');
function zk_save_billing_address($user_id){
    $address = $_POST;
    foreach ($address as $key => $field){
        // Only billing fields values
        if( strpos( $key, 'billing_' ) !== false ){
            // Condition to add firstname and last name to user meta table
            if($key == 'billing_first_name' || $key == 'billing_last_name'){
                $new_key = str_replace( 'billing_', '', $key );
                update_user_meta( $user_id, $new_key, $_POST[$key] );
            }
            update_user_meta( $user_id, $key, $_POST[$key] );
        }
    }
}

我如何更新注册时的自定义结帐字段?

这是我的注册页面

1个回答

2
主要错误是在账单部分使用以shipping_开头的结帐字段…
此外,最好使用复合钩子woocommerce_billing_fields,它将为您完成所有操作(因此无需将字段保存为用户元数据或订单项目元数据,因为 WooCommerce 已经处理了这些内容)。
所以,唯一需要替换的代码是(使用字段键billing_identifier而不是混淆的shipping_tc
add_filter( 'woocommerce_billing_fields' , 'add_custom_billing_field' );
function add_custom_billing_field( $fields ) {
    $fields['billing_identifier'] = array(
        'label' => __('TC Kimlik No', 'woocommerce'),
        'placeholder' => _x('Fatura İçin Gerekli', 'placeholder', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-wide'),
        'clear' => true
    );

    return $fields;
}

代码放在活动子主题(或活动主题)的functions.php文件中。已测试并可用。

该字段还将出现在“我的帐户”>“地址”>“编辑账单地址”中。


@ŞenolÜstün 我也在这里回答了你的第一个问题:https://dev59.com/2sDqa4cB1Zd3GeqPXy_j#66974237 - LoicTheAztec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接