I have custom fields in my custom post type. They should serve as a title and post slug for URL. Basically, whenever I change the content of the custom fields, the title field should react accordingly. E.g. if the field NAME contains ‘John’ and the SURNAME ‘Smith’, the title should transform to ‘John Smith’.
The users of the site will be unexperienced so they won’t understand the need of putting NAME and SURNAME and a separate title for that – that’s why I need it.
I know I can display custom field content instead of a title in my template, but that’s not the same. I also need the permalink to be amended accordingly.
So, to recap
My input:
custom field NAME = John
custom field SURNAME = Smith
What should happen:
post title = John Smith
permalink = john-smith (I presume it will process the title extracted from the custom fields as it would normally do)
I hope it’s clear now. Thanks indeed for any suggestions.
3 Answers
I think a good way to do what you want is hook the wp_insert_post_data
filter. Here you can change the title and slug of the post before it is saved to database:
add_filter( 'wp_insert_post_data', 'wpse_update_post_title_and_slug' );
function wpse_update_post_title_and_slug( $data ) {
//You can make some checks here before modify the post data.
//For example, limit the changes to standard post type
if( 'post' == $data['post_type'] ) {
//Add post meta to post title
$data['post_title'] = $_POST['the-name-field'] . ' ' . $_POST['the-surname-field'];
//Update the slug of the post for the URL
$data['post_name'] = sanitize_title( $data['post_title'] );
}
return $data;
}