1

I want to remove '@' from a user_meta when users register or update their profile.

Here is my code

add_action('edit_user_profile_update', 'update_extra_profile_fields');
add_action('personal_options_update', 'update_extra_profile_fields');
add_action( 'user_register', 'update_extra_profile_fields');

function update_extra_profile_fields($user_id) {
    if (isset($_POST['telegram_id'])) {
        $telegram_id = $_POST['telegram_id'];
        $telegram_id = str_replace('@', '', $telegram_id);
        update_user_meta($user_id, 'telegram_id', $telegram_id);
    }
}

So here update_user_meta is not working. It doesn't update the user meta when users register or update their profile from wordpress dashboard but when they update their profile from the frontend page that I've created for my website, it works!

In order to see what the problem is, I changed this line update_user_meta($user_id, 'telegram_id', $telegram_id); to this: $_POST['telegram_id'] = $telegram_id; and now it's working (But it's not a good solution). It seems that my function is run before another wordpress function which re updates the user_meta. How should I solve this problem?

1
  • did you find a solution to this?
    – Marc
    Dec 4, 2017 at 18:21

1 Answer 1

1

You answered yourself. It works on font page because it is designed to work that way. If you need to trigger your callback on "update_user_meta" you must use:

add_filter( 'update_user_metadata', 'your_function', 10, 4 );

with a function structured like this:

function your_function($done, $object_id, $meta_key, $meta_value){

    if($meta_key == 'first_name'){ // Look for certain meta_key in this case first_name
    
        if(str_contains($meta_value, '@')){ // If the meta_value contains the looked up value
            remove_filter('update_user_metadata', 'your_function'); // Remove the filter otherwise it loops and fails
            $my_value = str_replace('@', '', $meta_value); // Remove the value with replace
            $done = update_user_meta($object_id, $meta_key, $my_value); // Update again but now with your new value
        }
        
    }
    
    return $done; // Tells if operation was succeed
}

Here is documentation: https://developer.wordpress.org/reference/hooks/update_meta_type_metadata/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.