避免 WooCommerce Checkout Billing 表单覆盖默认的 Wordpress 用户数据

Avoid WooCommerce Checkout Billing form to overwrite default Wordpress user data

在数据库中我们有 metauser table 包含:
first_namelast_name 字段

这些是默认的 Wordpress 名字和姓氏。

我们还有:
billing_first_namebilling_last_name.

现在,当用户填写账单并继续结帐流程时, Woocommerce 使用账单名称字段中的新值更新这两个字段 (默认的)。

我已经尝试过很多使用动作的东西,例如:

woocommerce_before_checkout_billing_form

woocommerce_after_checkout_billing_form

还尝试更新元数据:

update_user_meta()

但它不起作用。

我希望它不覆盖默认的 first_name 和 last_name, 但仅在 billing_first_name 和 billing_last_name

中保留新值

我觉得默认流程是这样的
https://gist.github.com/claudiosanches/ae9a8b496c431bec661b69ef73f1a087

请问有什么帮助吗?

方法是使用挂钩在 woocommerce_checkout_update_customer 动作挂钩中的自定义函数:

add_action('woocommerce_checkout_update_customer','custom_checkout_update_customer', 10, 2 );
function custom_checkout_update_customer( $customer, $data ){

    if ( ! is_user_logged_in() || is_admin() ) return;

    // Get the user ID
    $user_id = $customer->get_id();

    // Get the default wordpress first name and last name (if they exist)
    $user_first_name = get_user_meta( $user_id, 'first_name', true );
    $user_last_name = get_user_meta( $user_id, 'last_name', true );

    if( empty( $user_first_name ) || empty( $user_last_name ) ) return;

    // We set the values by defaul worpress ones, before it's saved to DB
    $customer->set_first_name( $user_first_name );
    $customer->set_last_name( $user_last_name );
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

在 WooCommerce 3+ 中测试和工作