Hello! The nature of WP’s attachment system makes it pretty tricky to do. Here’s a snippet from a migration project I recently did that should point you in the right direction. You can see near the top that you’ve got to pass the doc_id, file_path, file_name, and date_created to the method.
protected function add_doc_attachment( $args ) {
$doc_id = $args['doc_id'];
$file_path = $args['file_path'];
$file_name = $args['file_name'];
$date_created = $args['date_created'];
buddypress()->bp_docs->attachments->set_doc_id( $doc_id );
$tmpfname = wp_tempnam( $file_name );
copy( $file_path, $tmpfname );
$file = array(
'error' => null,
'tmp_name' => $tmpfname,
'size' => filesize( $file_path ),
'name' => $file_name,
'type' => pathinfo( $file_path, PATHINFO_EXTENSION ),
);
$overrides = array(
'test_form' => false,
'test_size' => false,
'test_type' => false,
);
$sideloaded = wp_handle_sideload( $file, $overrides );
if ( isset( $sideloaded['error'] ) ) {
var_dump( $sideloaded ); die();
}
$attachment = array(
'post_date' => $date_created,
'post_mime_type' => $sideloaded['type'],
'post_title' => basename( $tmpfname ),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $doc_id,
);
$attachment_id = wp_insert_attachment( $attachment, $sideloaded['file'] );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $sideloaded );
wp_update_attachment_metadata( $attachment_id, $attach_data );
buddypress()->bp_docs->attachments->set_doc_id( 0 );
return $attachment_id;
}