Support

Account

Home Forums Backend Issues (wp-admin) Using 3 Fields to form a title fails on first publish.

Solving

Using 3 Fields to form a title fails on first publish.

  • Working on a function that uses three fields to automatically form a Post Title.
    However, I’m noticing that on first save, it only records the $client.
    When I hit Update Post, the $client, $location, and $service all work. At that point the Title, and Slug update with all three variables correctly.

    Should my hooks be one after the other like that? Not sure what I’m missing here…

    function aesthetics_acf_title( $value, $post_id, $field ) {
    
    	$client   = get_field( 'client', $post_id );
    	$location = get_field( 'location', $post_id );
    	$location = get_term( $location, $taxonomy );
    	$service  = get_field( 'case_study_service', $post_id );
    
    	$title    = $client->post_title . '-' . $location->name . '-' . $service->post_title;
    	$slug     = sanitize_title( $title );
    
    	$postdata = array(
    		'ID'         => $post_id,
    		'post_title' => $title,
    		'post_type'  => 'case-study',
    		'post_name'  => $slug,
    	);
    
    	wp_update_post( $postdata );
    
    	return $value;
    
    }
    add_filter( 'acf/update_value/name=client', 'aesthetics_acf_title', 10, 3 );
    add_filter( 'acf/update_value/name=location', 'aesthetics_acf_title', 10, 3 );
    add_filter( 'acf/update_value/name=service', 'aesthetics_acf_title', 10, 3 );
  • You should use a single acf/save_post filter with a priority > 10.

    The way you are doing it you are updating the post 3 times instead of once.

    Also, with a priority of 10, your filters may or may not be running before ACF actually saves the values. When dealing with ACF you should almost always use a priority > 10 unless you actually want to do something before ACF saves values. If that’s the case then you should always use a priority of < 10.

    I’m actually surprised that you’re not causing an infinite loop since this call wp_update_post( $postdata ); should be triggering ACF to re-save the values and then call your function again.

    You need to remove your filters before updating the post and read them after updating the posts.

    
    remove_filter($hook, $callback, $priority);
    wp_update_post($postdata);
    add_filter($hook, $callback, $priority, $accepted_args);
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.