How to set an attachments parent post id in code?

In WordPress – Attachments are their own post-type which means you just need to update the post using wp_update_post():

$media_post = wp_update_post( array(
    'ID'            => $attachment_id,
    'post_parent'   => $post_parent_id,
), true );

if( is_wp_error( $media_post ) ) {
    error_log( print_r( $media_post, 1 ) );
}

In the above you would pass both the Attachment ID and the Post ID which will be the attachment “parent” to the wp_update_post() function but we also want to make sure that if for whatever reason it cannot be updated – we add the WP_Error to the error_log so we can debug what went wrong.

You could also do an additional check before the wp_update_post() function to ensure the given attachment id is indeed an attachment. This is just another check so we don’t accidently update things we don’t need to:

if( 'attachment' === get_post_type( $attachment_id ) ) {
    // Update Post Code
}