I have a custom post type without title support and I’m trying to generate one from post’s taxonomies and custom fields. To do so, I’m using this code:
function custom_post_type_title_filter( $data , $postarr )
{
if ($postarr['post_type'] == 'cars'){
$id = get_the_ID();
$engine= ', '.get_post_meta($id, 'Engine', true).'l';
$terms = wp_get_object_terms($id, 'brand');
$abrand= ' '.$terms[0]->name;
$amodel = ' '.$terms[1]->name;
$data['post_title'] = $id.$abrand.$amodel.$engine;
}
return $data;
}
add_filter( 'wp_insert_post_data' , 'custom_post_type_title_filter' , 99, 2 );
Problem is, to make it work, I have to republish my post. It does not work with new post (it has no ID yet, I guess) and if I change custom field values in post, it won’t generate name from them yet, I’ll have to save it twice to get it done.
Can someone share a solution with example how it’s done properly?
Also, would be nice to be able to set custom slug too (different from the title).
You can try the following code.
Hook into the action
'save_post'
(example). You get the post ID as a parameter, and then you can do everything you did before. With one save action. 🙂