phparrayswordpressadvanced-custom-fieldsacfpro

Take multiple ACF user fields and combine them into one


I have some ACF user fields on posts where users can be selected, I would like to take those fields and combine them into another field. So basically the users in field 1 and field 2 show up in field 3. Here is what I have tried so far. The return format for the fields is user array.

add_action( 'acf/save_post', 'my_acf_save_post', 10 );
function my_acf_save_post( $post_id ) {
    // Get value of field 1
    $value1 = get_field( 'contractor', $post_id );
    // Get value of field 2 
    $value2 = get_field( 'architect', $post_id );

    update_field( 'project_user_select', $value1 . $value2, $post_id );
}

Solution

  • If there is a possibility of one of the values being empty I would write it something like this:

    // Get new value of field 1 or set value to null
    if(!empty(get_field( 'project_manager' )) {
      $value1 = get_field( project_manager', $post_id, false );
    } else {
      $value1 = '';
    }
    

    What this does is check if the field has entries, if it does it will assign the value to the variable $value. If the field does not have a value it will just declare the variable so when you try to add each of the $values to $merge it will still work because the variable has been declared.