post_name empty after wp_insert_post

Firstly, you shouldn’t use post_category, because according to the wordpress codex wp_insert_post():

‘post_category’ => [ array(, <…>) ] //post_category no longer exists, try wp_set_post_terms() for setting a post’s categories

Secondly, if you want the post title to be your slug you shouldn’t need to use the post_name parameter, because it gets constructed from the title by default. It’d be advisable to make sure your title is tag free, changing the according line to:

'post_title'    => wp_strip_all_tags( $article_title ),

If you really want to add the parameter post_name manually make sure to sanitize and assure uniqueness:

'post_name'   => wp_unique_post_slug( sanitize_title( $article_title ) ),

Aside from above points your code looks correct to me. The only other thing in mind about not getting a post name would be related to the value pending for the parameter post_status you have chosen, take a look at the source code yourself. What that means – if I’m not totally mistaken – is, that if the post status changes to a publishing state – publish or private for example – a update is performed and then the post name gets inserted to the database. Before – with post statuses auto-draft, draft or pending – that’s not happening.

Leave a Comment