1

I want to be able to generate titles automatically for a certain custom post type in WP admin. Been looking for a solution but I'm not sure if I'm headed in the right direction by adding this hook -

add_filter('the_title', 'cpt_title_filter');
function cpt_title_filter($title) {
    global $post;
    if ($post->post_type == 'time') {
        $title = 'sample headline';
    }
    return $title;
}

The generated title will be a date suffix, we'll leave a sample text there for now. This snippet is added just below of the "time" cpt setup in functions.php. As I have other cpts that don't require this function I also need to be able to check for a particular cpt in the function. What happens now is I get a blank field, and I assume the function is not in effect.

1 Answer 1

3

the_title filter filters the existing title when it's output on the front end. If you want to set a title when a post is created on the back end, you want to use the title_save_pre filter:

function wpa65253_time_title( $title ) {
    global $post;
    if ( isset( $post->ID ) ) :
        if ( empty( $_POST['post_title'] ) && 'time' == get_post_type( $post->ID ) )
            $title = 'sample headline';
    endif;
    return $title;
}
add_filter ( 'title_save_pre', 'wpa65253_time_title' );
2
  • Thanks for pointing that out! I can't get that snippet to work, however. Still just gives me a blank field. Sep 16, 2012 at 10:37
  • did you save draft or publish the post? you won't see anything until you take some sort of action.
    – Milo
    Sep 16, 2012 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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