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:
// 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:
- isn’t unique
- not sanitize, for example “Test” doesn’t became “test”
What am i doing wrong?
Firstly, you shouldn’t use
post_category
, because according to the wordpress codex wp_insert_post():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:If you really want to add the parameter
post_name
manually make sure to sanitize and assure uniqueness: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 parameterpost_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.