skip to Main Content

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 );
}

2

Answers


  1. Chosen as BEST ANSWER

    I was able to get this to work using array_merge.

    function my_acf_save_post_31( $post_id ) {
    // Get new value of field 1
    $value1 = get_field( project_manager', $post_id, false );
    // Get new value of field 2 
    $value2 = get_field( 'architect', $post_id, false );
    // Get new value of field 3 
    $value3 = get_field( 'contractor', $post_id, false );
    
    $merge = array_merge($value1,$value2,$value3);
    
    update_field( 'project_user_select', $merge, $post_id );// update 
    'other_field' with 'my_field' value
    }
    add_action( 'acf/save_post', 'my_acf_save_post_31', 10 );
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search