I just wanted to post the code that got this working without issues. I had an extra argument in the function that was never being used ( $post
).
function ccc_acf_update_fixture_post_title( $post_id ) {
if ( get_post_type( $post_id ) == 'fixture' ) {
$team = get_field( 'team', $post_id );
$venue = get_field( 'venue', $post_id );
$opponent = get_field( 'opponent', $post_id );
$date = new DateTime(get_field( 'date', $post_id ));
$new_title = $team . ' - ' . $venue . ' Vs ' . $opponent . ' on ' . $date->format('d/m/Y');
$new_slug = sanitize_title( $new_title );
$args = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $new_slug,
);
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'ccc_acf_update_fixture_post_title' );
// update the post, which calls save_post again
wp_update_post( $args );
// re-hook this function
add_action('save_post', 'ccc_acf_update_fixture_post_title');
}
}
add_action( 'save_post', 'ccc_acf_update_fixture_post_title' );
I’m still happy to take feedback if this function could be improved.