If you ever ran across the problem of auto-generated post titles – that look like this : “(no-title-1)” – then you might be interested in a snippet that will pull your custom fields / taxonomies to re-name all existing and to-be-created posts.
I use it a lot when I believe my client will not understand why the title needs to respect a specific format and might make things go wrong. I will then maybe deactivate the Title capability for a specific custom post type, created posts will then receive an automatically generated post name as above that will be confusing to identify in the post list.
If I want for example the post titles to be automatically created as such : “Year-Month-Day (custom tax)
– City name (custom field)
” so that I (and my client) can identify in a second what the post is about, only using information he already added himself in the custom fields I created for him, therefore I will use this snippet to create titles that can follow an idea of organization that fits my or the client’s needs.
If you only want to use 1 custom field :
<?php
add_filter( 'the_title', 'custom_post_title', 10, 2 );
function custom_post_title( $title, $id ) {
if ( get_post_type( $id ) == 'the-post-type' ) {
$title = get_post_meta( $id, 'my-custom-field', true );
}
return $title;
}
?>
If you want to use several custom fields :
Tip : you can customize the seperator (or just remove it) by modifying this part : ‘ – ‘. Also remove one “.” if removing the seperator.
<?php
add_filter( 'the_title', 'custom_post_title', 10, 2 );
function custom_post_title( $title, $post_id )
{
$custom_part_1 = get_post_meta( $post_id, 'custom-field-1', true );
$custom_part_2 = get_post_meta( $post_id, 'custom-field-2', true );
if( $custom_part_1 && $custom_part_2) {
$new_title = $custom_part_1 . ' - ' . $custom_part_2;
return $new_title;
}
return $title;
}
?>
If you want to use a taxonomy value with a custom field :
<?php
add_filter( 'the_title', 'custom_post_title', 10, 2 );
function custom_post_title( $title, $post_id ) {
$post_type = get_post_type( $post_id );
if ( $post_type == 'my-post-type' ) {
$custom_tax = get_the_terms( $post_id, 'my-taxonomy-slug' );
$custom_tax = $custom_tax[0]->name;
$custom_field = get_post_meta( $post_id, 'my-custom-field', true );
$title = $custom_tax . ' - ' . $custom_field;
}
return $title;
}
?>