There are no core (4.8.1) functions like detach_post()
or wp_update_attachment()
but we can use wp_update_post()
to detach attachments:
$result = wp_update_post( [
'ID' => $attachment_id,
'post_parent' => 0, // detach
] );
if( is_wp_error( $result ) ) {
// error
} else {
// success
}
We can also create a helper function (untested):
/**
* WPSE-279554: Detach Post
*
* @param int $post_id Post ID
* @return bool $return If post was successfully detached
*/
function wpse_detach_post( $post_id )
{
// Validate input - we only want positive integers
if( ! is_int( $post_id ) || $post_id < 1 )
return false;
$result = wp_update_post( [
'ID' => $post_id,
'post_parent' => 0, // detach
] );
return ! is_wp_error( $result );
}
Usage Example:
if( wpse_detach_post( $post_id ) ) {
// success
} else {
// error
}