最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

woocommerce offtopic - Update user meta when customer update their first name

programmeradmin0浏览0评论

I want to update the user meta when customer changes their first name.

here my code:

add_action( 'woocommerce_update_customer', 'can_editable_account_count' ); 
function can_editable_account_count( $customer_get_id ) {
    if ( ! is_account_page() && ! is_user_logged_in() ) {
       return;
    }
    
    update_user_meta($customer_get_id, 'can_editable_account', '0');
}

but is run whatever change customer made. I want only run if the specific field was changed.

I want to update the user meta when customer changes their first name.

here my code:

add_action( 'woocommerce_update_customer', 'can_editable_account_count' ); 
function can_editable_account_count( $customer_get_id ) {
    if ( ! is_account_page() && ! is_user_logged_in() ) {
       return;
    }
    
    update_user_meta($customer_get_id, 'can_editable_account', '0');
}

but is run whatever change customer made. I want only run if the specific field was changed.

Share Improve this question edited Feb 2, 2021 at 8:07 bueltge 17.1k7 gold badges62 silver badges97 bronze badges asked Feb 2, 2021 at 4:54 Baim WhelloBaim Whello 32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

That was a tricky one.

For the user meta update to happen only on first name update you will need the following.

  1. Create a constant that will contain the current user first name
  2. Check to see if the current user first name is different from the submitted user name on profile update

For the constant add the following line. I would suggest at the top of the function.php

define('USER_FIRST_NAME', get_user_meta(get_current_user_id(), 'first_name', true));

Now for the function

function can_editable_account_count( $customer_get_id ) {
    if ( ! is_account_page() && ! is_user_logged_in() ) {
        return;
    }

    // check if user submited the edit account form and if the first name field exists and has value
    if (isset($_POST['account_first_name']) && !empty($_POST['account_first_name'])) {
        // check if the current user name is not equal to the submited user name
        if ($_POST['account_first_name'] !== USER_FIRST_NAME) {
            update_user_meta($customer_get_id, 'can_editable_account', '0');
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论