Removing Images from a WordPress Post

delete_attachment( $attachment_id, true );
wp_delete_post( $attachment_id, true );

Are your best friends. You will need something like this:

$args = array(
    'post_type'    => 'attachment',
    'numberposts'  => null,
    'post_status'  => null,
    'post_parent'  => $post->ID,
    'post__not_in' => array(
        get_post_thumbnail_id( $post->ID )
    ),
);
$attachments = get_posts( $args );
if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        delete_attachment( $attachment_id, true );
        wp_delete_post( $attachment_id, true );
    }
}

The “true” statement defines that the attachments and their IDs are completely removed from the backend and filesystem. If you want to store them into the trash, then set it to false.

error code: 523