This question is relate to another one on WPSE:
Set post title from two meta fields
I am looking for a way to define a WP custom post type’s title and slug from a custom field (i.e. first name and last name). Such that if I enter “John” in the fname field and “Doe” in the lname field, the title would be “John Doe” and the slug would be “john-doe”.
The solution offered on thread linked above works but it requires that I “save draft” first before I hit “publish”. If I click on “publish” right away, the post title is nothing but a single dash/hyphen “-” and the slug is the post ID.
Anyone know how to make it work without the need to “save draft” first?
— Update —
Here’s the code I’m using. It’s based on the linked thread above.
function my_set_empname_title( $data , $postarr ) {
if($data['post_type'] == 'employees') {
$emp_fname = get_post_meta($postarr['ID'], 'emp_first_name', true);
$emp_lname = get_post_meta($postarr['ID'], 'emp_last_name', true);
$new_title = "$emp_fname" . '-' . "$emp_lname";
$post_slug = sanitize_title_with_dashes($new_title, '', $context = 'save');
$post_slugsan = sanitize_title($post_slug);
$data['post_title'] = $new_title;
$data['post_name'] = $post_slugsan;
}
return $data;
}
add_filter( 'wp_insert_post_data' , 'my_set_empname_title' , '99', 2 );
Try replacing
with
Replace the $_POST array keys with whatever the field name is on your form