How can I UN-attach media from a post?

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?

Related posts

Leave a Reply

3 comments

  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'
        "
    );