5

I'm having a trouble un-attaching media from a post without deleting it entirely from my site. Is there a simple way to unattach an image from a post for instance?

3 Answers 3

2

I learned from Brian Fegter that you can Un-attach an image from a post while participating in this question: Can I attach an image to a different post?

It isn't exactly "simple", but not to difficult. It's the only solution I've been able to find.

1

Is this what you're looking for?

e.g. Remove all image attachments from a post

//get all image attachments
$attachments = get_children( 
                    array(
                        'post_parent'       => $post->ID,
                        'post_mime_type'    => 'image',
                        'post_type'         => 'attachment'
                    ) 
                );

//loop through the array
if( !empty( $attachments ) ){   
    foreach( $attachments as $attachment ){
        // Update the post into the database
          wp_update_post( array(
                    'ID' => $attachment->ID,
                    'post_parent' => 0
                )
            );
    }
}

However, please take note of the caution when using wp_update_post.

Alternate method using $wpdb

//replace this with the above inside the foreach block;
global $wpdb;
$wpdb->query(
    "
    UPDATE $wpdb->posts 
    SET post_parent = 0
    WHERE ID = $attachment->id
        AND post_type = 'attachment'
    "
);
1

As of WordPress 4.2 this functionality is built in. Click the Detach link in media list view.

For older versions, there's a plugin which does the same thing: https://wordpress.org/plugins/unattach/

Unattach is a very simple plugin which allows detaching images and other media from WordPress posts, pages and other content types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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