以下は、私が書いた別のプラグインから取った私のやり方です。これはアップロードされたファイルに使用されます - $file は結果を含む投稿配列です - ただし、ディスクのどこかにファイルがある場合は、$filename をそれに設定できます (move_uploaded_file を削除します)。
$uploads = wp_upload_dir();
if ($uploads['error'] != '')
wp_die($uploads['error']);
$target_dir = $uploads['path'];
if (!file_exists ($target_dir))
mkdir ($target_dir);
$filename = $file['name'];
// If you get script file, it's a danger. Make it TXT file.
if ( preg_match( '/\.(php|pl|py|rb|cgi)\d?$/', $filename ) )
$filename .= '.txt';
$new_filename = wp_unique_filename( $target_dir, $filename );
$new_url = trailingslashit( $uploads['url'] ).$new_filename;
$new_filename = trailingslashit( $target_dir ) . $new_filename;
$upload_result[$filename]['new_filename']=$new_filename;
$upload_result[$filename]['valid'] = false;
$upload_result[$filename]['reason'] = '';
$upload_result[$filename]['url'] = $new_url;
// Detect whether the uploaded file is an image
$is_image = preg_match ('/(jpeg|png|gif)/i', $file['type']);
$type = ($is_image) ? "img" : "file";
if (!$is_image) {
$upload_result[$filename]['reason'] = "Sorry, you can only upload images.";
} else if (move_uploaded_file ($file['tmp_name'], $new_filename)) {
$upload_result[$filename]['valid'] = true;
$upload_result[$filename]['reason'] = '';
// Make sure the uploaded file is only readable for the owner process
@chmod( $new_file, 0400 );
//
// now attach this to the original post - not really required except that it will ensure
// that the image shows up on the right place in the media library and when viewing the post.
$wp_filetype = wp_check_filetype(basename($new_filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $new_filename, $commentData['comment_post_ID'] );
// need to include the image.php file so function wp_generate_attachment_metadata() works
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );