The post title is sometimes a little more complex than just a string of characters. It can contain multiple pieces of information about the post content. With more extensive use of custom post types, such a situation is increasingly common. Whether a normal blog post or a custom post type, you might be writing about a person. A trivial example would be that you want to make a list of people, one of whom would be ‘Joe Blogs’, and you want to sort your list of people by their last name. Here I will explain how I go about dealing with this problem.
There are two choices. You can either split the post title into parts and try to work out where the pieces go, or you can collect the pieces individually and assemble them together to create your post title. The former seems at first easier and straight forward, whilst the latter is more cumbersome. Both for the user and to write the code for. I was in two minds when faced with this, the latter option would be my natural choice, but it involves re-inventing the wheel (It would need to re-write the core post_title and post_name values). And I am very keen on not fudging around with core code.
I fired off and email to the WordPress hackers mailing list. The replies were pretty quick, and they all agreed with me. Back to my example problem. I have a custom post type ’speaker‘ that can handle up to four parts to the full name. Allowing me to handle something like ‘Dr Joe Blogs MBE’.
How to handle complex names (of people) in your posts
add_filter('wp_insert_post_data', 'tcb_auto_generate_name_title');
function tcb_auto_generate_name_title($data){
global $post;
if( $post->post_type != 'speaker' ) return $data;
$speaker_meta['name_prefix'] = trim($_POST['name_prefix']);
$speaker_meta['name_first'] = trim($_POST['name_first']);
$speaker_meta['name_last'] = trim($_POST['name_last']);
$speaker_meta['name_suffix'] = trim($_POST['name_suffix']);
$fullname = array($speaker_meta['name_prefix'], $speaker_meta['name_first'], $speaker_meta['name_last'], $speaker_meta['name_suffix']);
$fullname = implode(' ', $fullname);
$slug = wp_unique_post_slug(sanitize_title($fullname), $post->ID, $post->post_status, $post->post_type, $post->post_parent);
$data['post_title'] = $fullname;
$data['post_name'] = $slug;
return $data;
}
And there you have it. With this you get to keep the full post title and post slug, and make it easy to order your speakers by last name. Not only does it look good, but it helps with search engine optimisation.