Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.