I am using this code snippet to add the custom meta entered by customer from the custom field license_plate when they add a new vehicle to their account. how ever upon saving the post for whatever reason a second time – it will add the same meta again …this does not happen a third or fourth time it stops at 2 entries meaning duplicate – note: when erasing re-saving it will display the license plate 2x at most after updating many times. I believe there needs to be something in this code at the update_post part but how to code this I do not know. Can someone help me with this where it can check is the post title has already been filled in previous and then leave alone if that is true.
I am using cpt-UI for the custom posts and ACF for the fields.
// Auto-populate post title with ACF fields created before hand
function engx_auto_generate_vehicles_post_title( $value, $post_id, $field ) {
//$date = strtotime(get_field('license_plate', $post_id));
$license = get_field('license_plate', $post_id). ' ' . $value; //get the value of the meta inputed by customer
$title = $license; //actual usage
//$formatted_date = date_i18n('d M Y', $date); //saved for use case time
//$title = $formatted_date .' - '. $license; // this was kept as example with multiple meta usage
$slug = sanitize_title( $title ); //save meta
$postdata = array(
'ID' => $post_id,
'post_title' => $title, //Use the meta $title as the New auto generated Title for the newly created post the customer just created
'post_type' => 'vehicles', //The Custom Post Type Name
'post_name' => $slug
);
wp_update_post( $postdata );
return $value;
}
//add_filter('acf/update_value/name=date', 'jb_update_postdata', 10, 3);
add_filter('acf/update_value/name=license_plate', 'engx_auto_generate_vehicles_post_title', 10, 3); //acf hook from where to fetch this specific field data - is from acf documentation
Any help is greatly appreciated.
2
Answers
I figured it out found the peice of code needed to verify if empty first as follows
You are probably better off using
acf/save_post
to handle events when creating new or updating existing vehicle posts…https://www.advancedcustomfields.com/resources/acf-save_post/
See example below…