<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/*** アップロード時にファイル名をEXIFの撮影日時に変更（重複回避：アンダーバー付与） ***/
function haup_rename_file_by_exif_on_upload($file) {
	$type = $file['type'];

	if (strpos($type, 'image') === false) {
		return $file;
	}

	$temp_path = $file['tmp_name'];
	$exif = @exif_read_data($temp_path);
    
	$timestamp = null;

	if (!empty($exif['DateTimeOriginal'])) {
		$timestamp = strtotime($exif['DateTimeOriginal']);
	} elseif (!empty($exif['DateTime'])) {
		$timestamp = strtotime($exif['DateTime']);
	}

	if ($timestamp) {
		$base_name = date('Y-m-d_H-i-s', $timestamp);
		$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        
		$uploads = wp_upload_dir();
		$target_path = $uploads['path'];

		// 最初は番号なしでチェック
		$final_name = $base_name . '.' . $extension;
		$counter = 1;

		// 重複があれば「_1, _2...」を付与
		while (file_exists($target_path . '/' . $final_name)) {
			$final_name = $base_name . '_' . $counter . '.' . $extension;
			$counter++;
		}

		$file['name'] = $final_name;
	}

	return $file;
}
add_filter('wp_handle_upload_prefilter', 'haup_rename_file_by_exif_on_upload');