Support

Account

Home Forums ACF PRO Use acf field to create post title

Helping

Use acf field to create post title

  • Hi,

    I need to use acf field to create the title of my custom post. All working, but I have a problem.

    Here is my code:

    function dimension_update_postdata( $value, $post_id, $field ) {
    $code = get_field(‘dimension_code’, $post_id);
    $no = get_field(‘dimension_no’, $post_id);

    $title = $no .’ – ‘. $code;
    $slug = sanitize_title( $title );

    $postdata = array(
    ‘ID’ => $post_id,
    ‘post_title’ => $title,
    ‘post_type’ => ‘dimension’,
    ‘post_name’ => $slug
    );

    wp_update_post( $postdata );

    return $value;
    }
    add_filter(‘acf/update_value/name=dimension_code’, ‘dimension_update_postdata’, 10, 3);
    add_filter(‘acf/update_value/name=dimension_no’, ‘dimension_update_postdata’, 10, 3);

    My problem is : when I publish/save the post for the first time, only the first acf field (dimension_code) of my acf form is updated. When I’m going in the list of posts, my custom post have this title – HSL, the first field is not there. But if I return to edit my post and I save again my post title is ok (eg. 644 – HSL).

    What happening, why only the first field is use at the first time I save my post ?

    If I replace the two add_filter by this (without the name field) :
    add_filter(‘acf/update_value’, ‘dimension_update_postdata’, 10, 3);
    The title of my post is ok the first time I save my post?!?
    I don’t understand.

    Anybody have an idea. I don’t if is a bug or only a problem with my code.

    Config:
    WP 4.2.2
    WPML
    ACF Pro (the last one)

    Thanks

  • I’ve been using this…give it a try

    //Auto add and update Title field:
      function my_post_title_updater( $post_id ) {
    
        $my_post = array();
        $my_post['ID'] = $post_id;
    
    // custom post type
        $foo           = get_field('foo');
    
        if ( get_post_type() == 'foo' ) {
          $my_post['post_title'] = get_field('acf_title_slug');
        } 
    
        // Update the post into the database
        wp_update_post( $my_post );
    
      }
       
      // run after ACF saves the $_POST['fields'] data
      add_action('acf/save_post', 'my_post_title_updater', 20);
    //END Auto add and update Title field:
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Use acf field to create post title’ is closed to new replies.