0

I created a custom post type with different input fields. For example first name and last name.

So I want this inputs as title in the post column-list. To do this I used the filter option:

add_filter( 'the_title', function( $title ) { 
    $title_firstname = esc_html( get_post_meta( get_the_ID(), 'first_name', true ) ); 
    $last_name = esc_html( get_post_meta( get_the_ID(), 'last_name', true ) );

    $title = $first_name . ' ' . $last_name;
    return  $title; 
} );

Okay this works for me but there is one problem:

All titles form default-posts and pages are gone.

Whta can I do to change only my custom post titles?

Hope somebody can help me :)

Kind reagrds,

Jop

0

When you're using get_post_meta() and the post meta doesn't exist for that post (or page or custom post type), then the function returns either an empty array or empty string depending on if the third parameter is false (default) or true. Since you're passing true as that parameter, you can check if either the first name or last name is equal to an empty string. If so, then you can return the $title unaltered.

You can also add a check using is_singular() if you only want the filter applied on certain post types.

add_filter( 'the_title', function( $title, $id ) { 
    //* Only use this filter on `your-custom-slut` post types
    if( ! is_singular( 'your-custom-slug' ) ) {
      return $title;
    }
    $fn = esc_html( get_post_meta( $id, 'first_name', true ) ); 
    $ln = esc_html( get_post_meta( $id, 'last_name', true ) );
    //* Use default if either the `first_name` or `last_name` isn't defined
    return ( '' === $fn || '' === $ln ) ? $title : $fn . ' ' . $ln;
}, 10, 2 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.