Build the Post Title From ACF Fields
Sets a post's title and slug from ACF fields when it is saved, for example a team member's first and last name, so editors never type it twice.
Opens WPIDE on
Code
// Post type and the fields that make up the title.
$wpide_acf_title_type = 'team';
$wpide_acf_title_fields = array( 'first_name', 'last_name' );
add_action( 'acf/save_post', function ( $post_id ) use ( $wpide_acf_title_type, $wpide_acf_title_fields ) {
if ( ! is_numeric( $post_id ) || get_post_type( $post_id ) !== $wpide_acf_title_type || ! function_exists( 'get_field' ) || wp_is_post_revision( $post_id ) ) {
return;
}
$parts = array();
foreach ( $wpide_acf_title_fields as $name ) {
$value = get_field( $name, $post_id );
if ( is_scalar( $value ) && '' !== trim( (string) $value ) ) {
$parts[] = trim( (string) $value );
}
}
$title = sanitize_text_field( implode( ' ', $parts ) );
if ( '' === $title || get_the_title( $post_id ) === $title ) {
return;
}
wp_update_post( array(
'ID' => (int) $post_id,
'post_title' => $title,
'post_name' => wp_unique_post_slug( sanitize_title( $title ), (int) $post_id, get_post_status( $post_id ), $wpide_acf_title_type, 0 ),
) );
}, 20 );
Notes
Set the post type and the fields joined into the title. Runs after ACF saves its values.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.