Updated version…
<?php
/**
* @param $posts array
* @return false|string
*/
function create_relationship_title($posts)
{
// set empty net title array
$new_title = [];
// if posts is not an array then return false
if (!is_array($posts)) return false;
// loop through each post
foreach ($posts as $post) {
// add the current post title to new title array
$new_title[] = $post->post_title;
}
// join all the related post titles together separated by a comma
$new_title = implode(', ', $new_title);
// return the new title
return $new_title;
}
/**
* @param $post_id int
*/
function lh_acf_save_post($post_id ) {
// check we are on the correct post type
if(get_post_type($post_id) <> 'alerts') return;
$new_title="";
// Get title from 'companies' CPT acf field 'company_name'
if ( get_post_type( $post_id ) == 'alerts' ) {
$relationships = get_field( 'route_affected_by_this_alert', $post_id );
$new_title = create_relationship_title($relationships);
}
// get our product object
$post = get_post($post_id);
// generate our post title
if($post->post_status == 'publish' || $post->post_status == 'draft') {
// remove the action
remove_action('acf/save_post', 'lh_acf_save_post', 20);
// update the post object
$post->post_title = $new_title;
$post->post_name = sanitize_title($new_title);
// update post
wp_update_post($post);
// re add the action
add_action('acf/save_post', 'lh_acf_save_post', 20);
}
// finally, return
return;
}
// construct your action here
add_action( 'acf/save_post', 'lh_acf_save_post', 20 );