Support

Account

Home Forums Front-end Issues Setting a post title from an ACF field when creating a post via acf_form?

Helping

Setting a post title from an ACF field when creating a post via acf_form?

  • Ugh, I’ve been researching for hours now and just can’t get this to work. I have a custom post type called “Equipment”. I made a page to allow a user to create a new post from the frontend. This page has an acf_form on it. I don’t want to use ‘post_title’ => true, I need to use a custom field to set the post title.

    I was able to use acf/save_post to correctly update the title and slug when I update a post from the frontend using an acf_form, but not when I initially create the post. This is the code I used:

    On my page template for “example.com/create-equipment”:

    <form id="equipment" class="acf-form" action="" method="post">
    
            <?php acf_form( array(
              'id'         => 'create-equipment',
              'post_id'    => 'new_post',
              'new_post'   => array(
                'post_status' => 'publish',
                'post_type'   => 'hb_equipment',
              ),
              'fields'     => array(
                'equipment-name',
                'equipment-type',
                'equipment-cost_number',
                'equipment-weight',
                'equipment-description',
              ),
              'form'      => false,
              'honeypot'  => false,
              'return'    => '%post_url%',
            )); ?>
    
            <div class="acf-form-submit">
              <input class="acf-button button button-primary button-large" type="submit" value="Create">
            </div>
    
          </form>

    In functions.php:

    function dwp_save_post( $post_id ) {
    
        $new_title = get_field('equipment-name', $post_id);
        $new_slug = $post_id . '-' . $new_title;
    
        $new_post = array(
          'ID'            => $post_id,
          'post_title'    => $new_title,
          'post_name'     => $new_slug,
        );
    
        wp_update_post( $new_post );
    }
    add_action('acf/save_post', 'dwp_save_post', 20);

    That correctly sets my urls to “example.com/equipment/123-post-title”, but only when I’m updating an existing post, not when creating a brand new one.

    I’ve also tried using acf/pre_save_post but I wasn’t able to get it to do anything at all.

  • Do you still need an answer?

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

The topic ‘Setting a post title from an ACF field when creating a post via acf_form?’ is closed to new replies.