'', 'post_parent' => 0, ), $args ); return wp_insert_attachment( $r, $r['file'], $r['post_parent'], true ); } /** * Saves a file as an attachment. * * @since 4.4.0 * @since 6.2.0 Returns a WP_Error object on failure. * * @param string $file Full path to the file to create an attachment object for. * The name of the file will be used as the attachment name. * @param int $parent_post_id ID of the post to attach the file to. * * @return int|WP_Error The attachment ID on success, WP_Error object on failure. */ public function create_upload_object( $file, $parent_post_id = 0 ) { $contents = file_get_contents( $file ); $upload = wp_upload_bits( wp_basename( $file ), null, $contents ); $type = ''; if ( ! empty( $upload['type'] ) ) { $type = $upload['type']; } else { $mime = wp_check_filetype( $upload['file'] ); if ( $mime ) { $type = $mime['type']; } } $attachment = array( 'post_title' => wp_basename( $upload['file'] ), 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $parent_post_id, 'post_mime_type' => $type, 'guid' => $upload['url'], ); // Save the data. $attachment_id = wp_insert_attachment( $attachment, $upload['file'], $parent_post_id, true ); if ( is_wp_error( $attachment_id ) ) { return $attachment_id; } wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) ); return $attachment_id; } }