wp_publish_post breaks permalinks

I’m creating a system, where some custom post drafts are being prepared, and after certain actions taken by moderators it is being automatically published.

So, first I create post draft like that:

$newpost = array(
    'post_title'    => 'Raport '.date("Y-m-d"), 
    'post_content'  => 'Add your content here',
    'post_type'     => 'raport',
    'post_status'   => 'draft',
    'post_author'   => $userid
);

wp_insert_post($newpost);

This draft awaits for admins to take some action. It can be edited etc., and on edit page the permalink designed for this post is OK.

After admins perform certain actions, the system publishes the post automatically:

wp_publish_post($id); 

But after that the post’s permalink is being broken. Instead of standard permalink (that wa visible on edit page):

http://my-website.pl/raport/post-slug-name

the post’s permalink after wp_publish_post looks like that:

http://my-website.pl/raport/

which directs to custom post’s type archive page, not to the post itself.

How can I fix it and publish these posts without breaking the permalinks?

2 Answers
2

Although the name of the function wp_publish_post() suggests that it can be used to publish a post it should obviously not be used to publish a draft post programmatically.

The way to do so is to use wp_update_post() and set the post status manually to publish:

<?php
// Update post with the ID 42
$postData = [ 'ID' => 42, 'post_status' => 'publish' ];
wp_update_post( $postData );

This will create a valid value for the post_name field and thus a proper permalink.

The function wp_publish_post() is used by WordPress only for publishing future posts during a scheduled hook (see check_and_publish_future_post()). The reason why this won’t break permalinks is, that posts with status future already have a valid value for post_name created by wp_insert_post().

Leave a Comment