Support

Account

Home Forums General Issues Auto generate post_title with acf_form

Solving

Auto generate post_title with acf_form

  • Hi acf-community!

    I use acf_form to create posts the custom post type “tickets” from the wordpress frontend:

    <?php
    
         acf_form(array(
            'post_id'       => 'new_post',
            'post_title'    => false,
            'post_content'  => false,
             'new_post'     => array(
                  'post_type' => 'tickets',
                  'post_status' => 'publish'
             ),
             fields' => array('field_5ba8b0c6a5116', 'field_5ba8b08c96be1'),
         );
    
    ?>

    I use the following filter to create a custom post title. This is working perfectly when i create a post of the cpt “tickets” in the backend but its not working when the post is created from the frontend with acf_form:

    add_filter('title_save_pre','auto_generate_post_title');
    
    function auto_generate_post_title($title) {
       global $post;
       if (isset($post->ID)) {
            if (empty($_POST['post_title']) && 'tickets' == get_post_type($post->ID)) {
                // get the current post ID number
                $id = get_the_ID();
                // add ID number with order strong
                $title = 'ticket-'.$id;
            } 
       }
       return $title; 
    }

    What am i doing wrong?

  • I’m not sure of all of the details of the title_save_pre hook. If it is firing for acf_form() saves then most likely the global $post has no value. You will also not have a way to get the post or post ID in this function since the value of the $_POST post ID will likely be new_post.

    It is always best to use the acf/save_post hook when dealing with ACF, front end or back https://www.advancedcustomfields.com/resources/acf-save_post/

    You could also create your own acf/pre_save_post for the front end https://www.advancedcustomfields.com/resources/acf-pre_save_post/

  • Pretty sure you can add the title to the new post like so:

    <?php
    
         acf_form(array(
            'post_id'       => 'new_post',
            'post_title'    => false,
            'post_content'  => false,
             'new_post'     => array(
                  'post_type' => 'tickets',
                  'post_status' => 'publish',
    'post_title' => 'my title'
             ),
             fields' => array('field_5ba8b0c6a5116', 'field_5ba8b08c96be1'),
         );
    
    ?>

    Seems nicer, but you don’t have access to the new post ID 🙁

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.