post_name empty after wp_insert_post

I’m writing an external tool that inserts post in wordpress (I’m using the wordpress functions).
I read also this discussion: wp_insert_post does not write my post_name

But my problem is a little different. I do the insert of post, but post_name is empty.
The code is:

Read More
// Create post object
$my_post = array(
'post_title'    => $article_title,
'post_name'   => $article_title,
'post_content'  => $article_content,
'post_status'   => 'pending',
'post_author'   => 1,
'post_category' => array(8,39)
);

// Insert the post into the database
wp_insert_post( $my_post );

I tried with and without the post_name, but the result did not change. I also tried after:

$post_ID = (int) $wpdb->insert_id;
$post_name = wp_unique_post_slug($article_title, $post_ID, $post_status, $post_type, $post_parent);
$where = array( 'ID' => $post_ID );
$wpdb->update( $wpdb->posts, array( 'post_name' => $post_name ), $where );

But so for example, insert the post_name but:

  1. isn’t unique
  2. not sanitize, for example “Test” doesn’t became “test”

What am i doing wrong?

Related posts

1 comment

  1. 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.

Comments are closed.