Auto-Generate Post Title from ACF Fields

Automatically set the post title and slug from ACF field values on save, removing the need for editors to type a title.

php hooks
|

Automatically set the post title and slug from ACF field values on save, removing the need for editors to type a title.

Use acf/save_post to generate a title from field values after they’re saved:

<?php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( get_post_type( $post_id ) !== 'staff' ) {
        return;
    }

    $first_name = get_field( 'first_name', $post_id );
    $last_name  = get_field( 'last_name', $post_id );

    if ( ! $first_name || ! $last_name ) {
        return;
    }

    $title = $first_name . ' ' . $last_name;

    // Remove this action to prevent infinite loop.
    remove_action( 'acf/save_post', __FUNCTION__, 20 );

    wp_update_post( [
        'ID'         => $post_id,
        'post_title' => $title,
        'post_name'  => sanitize_title( $title ),
    ] );

    add_action( 'acf/save_post', __FUNCTION__, 20 );
}, 20 );

A more complex example — generate a title with a date:

<?php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( get_post_type( $post_id ) !== 'event' ) {
        return;
    }

    $name = get_field( 'event_name', $post_id );
    $date = get_field( 'event_date', $post_id );

    if ( ! $name ) {
        return;
    }

    $title = $name;
    if ( $date ) {
        $title .= ' — ' . date( 'j M Y', strtotime( $date ) );
    }

    remove_action( 'acf/save_post', __FUNCTION__, 20 );

    wp_update_post( [
        'ID'         => $post_id,
        'post_title' => $title,
        'post_name'  => sanitize_title( $title ),
    ] );

    add_action( 'acf/save_post', __FUNCTION__, 20 );
}, 20 );

Tip: Hide the default title field in the editor by setting “Supports > Title” to false in your custom post type registration, since editors won’t need to enter it manually.

Related Snippets

Stay Updated

Get ACF tips and new extensions in your inbox

No spam. Unsubscribe anytime.