1

I want to detach/unattach an image from the page it's currently attached to -- by using PHP, instead of the "Detach" link in the Media Library.

I found this (in /wp-admin/includes/media.php#3164):

$result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" );

So I assume I could just use this in my own PHP, replacing the $ids_string with the ID of the attachment to remove.

Is there a better way?

2

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
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.