Hi there,
I’m working on a site where people fill out a form with their first and last name. I want to combine those names into the Post Title field.
As I understand it, I can use the action acf/save_post
to update the post after ACF first creates it.
Should I still be using the acf/pre_save_post
filter?
Is there a way to filter the posted values before saving (so that I can set up the title field BEFORE the post is saved?)
Here is how I would go about it, untested code.
First a function to extract the names from $_POST, by adding an action to acf/save_post()
function pre_save_user_fullname($post_id){
if( empty($_POST['acf']) ) { return; }
$firstname = $_POST['acf']['FIRST NAME FIELD KEY'];
$lastname = $_POST['acf']['LAST NAME FIELD KEY'];
$fullname = $firstname.' '.$lastname;
return $fullname;
}
add_action('acf/save_post', 'pre_save_user_fullname', 21);
Then modifying the post data before it is written to db, by filtering wp_insert_post_data();
function user_fullname_as_post_title( $data, $postarr ) {
if ( ! $postarr['ID'] ) return $data;
if ( $postarr['post_type'] !== 'YOUR_POST_TYPE' ) return $data;
$post_id = $postarr['ID'];
$fullname = pre_save_user_fullname($post_id);
if( empty($fullname) ) { return $data; }
$data['post_name'] = $fullname;
return $data;
}
add_filter( 'wp_insert_post_data', 'user_fullname_as_post_title', 99, 2 );
If it doesn’t work, I hope it at least helps.