Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active July 24, 2024 18:11
Show Gist options
  • Save sabrina-zeidan/2d22ab7f23dab76e3cd25bf8d3e92377 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/2d22ab7f23dab76e3cd25bf8d3e92377 to your computer and use it in GitHub Desktop.
When you have ACF User fields like first name and last name and you need to keep that in sync with what is entered in WordPress user profile (works both ways)
//If both changed at the same time - custom field value will be applied as it fires later, set 30 to change it add_action( 'profile_update', array($this, 'update_acf_fields'), 30, 2 );
class Sync_ACF_with_User_Profile_Class {
static public $sync_pair = array(
array( 'acf' => 'member_name', 'profile_field' => 'first_name'), //add acf field name according to your setup
array( 'acf' => 'member_lastname', 'profile_field' => 'last_name')// add more rows to sync any other fields as well
);
public function __construct() {
add_action( 'profile_update', array($this, 'update_acf_fields'), 10, 2 ); //when profile is updated -> update ACF
add_action('updated_user_meta', array($this, 'update_user_profile_fields'),10,4); // when ACF is updated -> update profile
add_action('added_user_meta', array($this, 'update_user_profile_fields'),10,4); // when ACF is added -> update profile
}
public function update_user_profile_fields($meta_id, $user_id, $meta_key, $meta_value){
$user_data = get_userdata( $user_id );
foreach (Sync_ACF_with_User_Profile_Class::$sync_pair as $sync_pair){
if ($sync_pair['acf'] == $meta_key ){
$profile_field = $sync_pair['profile_field'];
$profile_field_value = $user_data->$profile_field;
$update = ($profile_field_value == $meta_value) ? false : wp_update_user(['ID' => $user_id, $profile_field => $meta_value]);
}
}
}
public function update_acf_fields( $user_id, $old_user_data ) {
$user_data = get_userdata( $user_id );
foreach (Sync_ACF_with_User_Profile_Class::$sync_pair as $sync_pair){
$meta_value = get_user_meta($user_id, $sync_pair['acf'] , true);
$profile_field = $sync_pair['profile_field'];
$profile_field_value = $user_data->$profile_field;
$update = ($profile_field_value == $meta_value) ? false : update_user_meta($user_id, $sync_pair['acf'], $profile_field_value );
}
}
}
$sync = new Sync_ACF_with_User_Profile_Class();
add_action( 'wp_loaded', array( $sync, '__construct' ) );
@waqasraza123
Copy link

You saved the day, thank you!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment