G.I.George
G.I.George

Reputation: 21

Can't get post ID and category using wp_insert_post_data

I would like to create post titles automatically. The post title is made from the category and category ID before the post is created in the database but does not get the category and ID.

Any help will be much appreciated, Thank You.

function my_post_titles($data, $postarr){

        $postid = $postarr['ID'];
        $postcategory = $postarr['post_category'];

        $data['post_title'] = $postcategory."-".$postid; 

return $data;

}
add_filter('wp_insert_post_data', 'my_post_titles', '99', 2 );

Upvotes: 1

Views: 973

Answers (1)

Thai Duong Tran
Thai Duong Tran

Reputation: 2522

Couple of things to be aware of here: wp_insert_post_data is the filter used by wp_insert_post to allow changes to its first parameter, so to understand your problem, you should check how wp_insert_post works.

https://developer.wordpress.org/reference/functions/wp_insert_post/

Essentially, if the post you are creating a new post, then it should not have any ID (as it's not even created and saved to the database yet). To have access to the post ID, I suggest you use save_post hook rather than wp_insert_post. save_post is the action triggered after the post is created or updated. For example:

add_action('save_post', function($post_id) {
   $title = get_the_title($post_id);

   if ($title) {
     return; // if the post has already has a title, then do nothing
   }
   // Otherwise, update the post title here
});

Also, $postarr['post_category'] is an array, not a string, so to get the correct information, you must convert it to string before concat it with the post_id.

Upvotes: 1

Related Questions