Auto create post title in admin

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.

Related posts

Leave a Reply

1 comment

  1. 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' );