Set Custom Post Type title to the Post’s Date

I have a custom post type, called ‘status’ and I have disabled ‘title’ in the post type. Right now it’s setting all posts to have the title “Auto Draft”. I want to set up a way to set the title to be the post’s date. I think I should be using ‘wp_insert_post_data”. Right now I am using the following code but it is not working:

function status_title_filter( $data , $postarr )
{

if ($postarr['post_type'] == 'status'){
    $date = $data['post_date'];
    $data['post_title'] = $date;
}
return $data;
}

add_filter( 'wp_insert_post_data' , 'status_title_filter' , '99' );

Thanks in advance for solving my simple problem. I’m a sort of novice when it comes to this kind of things.

Related posts

Leave a Reply

3 comments

  1. Despite what the Codex says, $postarr doesn’t always get passed in, so you should just use $data. $data isn’t a meaningful variable name, though, so I prefer $cleanPost. I’d also try removing the priority on the filter, since it’s not usually necessary. It’s also a good idea to set the slug (post_name) in addition to the title, and to avoid running the code on auto-drafts and trash/untrash operations. See if this works instead:

    function status_title_filter( $cleanPost )
    {
        if( $cleanPost['post_type'] == 'status' && $cleanPost['post_status'] != 'auto-draft' && $_GET['action'] != 'trash' && $_GET['action'] != 'untrash' )
            $cleanPost['post_title'] = $cleanPost['post_name'] = $cleanPost['post_date'];
    
        return $cleanPost;
    }
    
    add_filter( 'wp_insert_post_data', 'status_title_filter' );
    

    Update: I think the reason you don’t see $postarr is because by default action callbacks only accept one parameter. If you want more then you have to specify that in the hook, like add_action( 'wp_insert_post_data', 'my_callback_function', 10, 2). That would set the priority to 10 and the number of arguments to 2.

  2. I know it’s a late, but you can set the title to the postdate right before you create the post.

    $postarr['title'] = current_time('mysql');
    $postarr['post_type'] = 'myposttype';
    wp_insert_post($postarr);
    

    HTH