【问题标题】:Save WooCommerce checkout custom field as user meta data将 WooCommerce 结帐自定义字段保存为用户元数据
【发布时间】:2021-07-02 09:01:48
【问题描述】:

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

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

顺便说一句,我在注册字段中使用了结帐字段。

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] );
        }
    }
}

我可以通过注册更新自定义结帐字段做什么?

这里是my registration page

【问题讨论】:

    标签: php wordpress woocommerce checkout usermetadata


    【解决方案1】:

    主要错误是在计费部分使用了字段键以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 文件中。经过测试并且可以工作。

    该字段将另外出现在我的帐户 > 地址 > 编辑帐单地址中。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2021-07-23
    • 2023-03-05
    相关资源
    最近更新 更多