1

I want to generate post title from first name and last name which are two fields. The posts are generated in WS Form and saved with no title.

I tried this code however it does not seem to work. Any thoughts?!

    function set_post_title_from_acf($post_id){

        $my_post = array();
        $my_post['ID'] = $post_id

        if (get_post_type($post_id) == 'staff'){

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

            $my_title = $first_name . ' ' . $last_name;
            $my_post['post_title'] = $my_title;
            $my_slug = sanitize_title($my_title);
            $my_post['post_name'] = $my_slug;
            wp_update_post($my_post);

        }

    }
    add_action('save_post','set_post_title_from_acf',20);

1 Answer 1

0

The $post_id value get in save_post hook might be revision ID. So to retrieve real post ID, you can use this function wp_is_post_revision()

Try to change your code as follows,

function set_post_title_from_acf($post_id) {
    
    // If this is a revision, get real post ID
    if ( $parent_id = wp_is_post_revision( $post_id ) ) 
        $post_id = $parent_id;

    $my_post = array();
    $my_post['ID'] = $post_id;

    if (get_post_type($post_id) == 'staff') {

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

        $my_title = $first_name . ' ' . $last_name;
        $my_post['post_title'] = $my_title;
        $my_slug = sanitize_title($my_title);
        $my_post['post_name'] = $my_slug;
        
        // unhook this function so it doesn't loop infinitely
        remove_action( 'save_post', 'set_post_title_from_acf' );
        
        wp_update_post($my_post);
        
        // re-hook this function
        add_action( 'save_post', 'set_post_title_from_acf' );
        
        
    }
}

add_action('save_post', 'set_post_title_from_acf');

Nb: If we are calling wp_update_post() inside save_post hook, it will create an infinite loop. To avoid this, unhook the function before calling the function and then re-hook it as in the above code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.