X. // Or we can match by filename against the files in the source directory. // Let's iterate the source directory 'quienes_somos', get the filenames, // and find attachments with those filenames created TODAY. $target_rel_path = 'quienes_somos'; $uploads = wp_upload_dir(); $base_dir = $uploads['basedir']; $target_dir = $base_dir . '/' . $target_rel_path; if (!file_exists($target_dir)) { die("Directory not found: $target_dir\n"); } $files = glob("$target_dir/*"); $filenames = []; foreach ($files as $file) { if (is_file($file) && !in_array(pathinfo($file, PATHINFO_EXTENSION), ['html', 'php'])) { $filenames[] = basename($file); } } echo "Found " . count($filenames) . " files in source directory.\n"; if (empty($filenames)) { die("No files to process.\n"); } // Prepare SQL to find attachments with these filenames // We filter by post_date LIKE '2026-02-14%' to only catch today's imports // to avoid messing with older files that might have same names. $placeholders = implode(',', array_fill(0, count($filenames), '%s')); $sql = "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_date LIKE '2026-02-14%' AND ( post_title IN ($placeholders) OR guid REGEXP '" . implode('|', array_map('preg_quote', array_slice($filenames, 0, 50))) . "' )"; // REGEXP is risky with 1000 files. Let's stick to post_title/post_name matching. // WordPress sanitizes filenames, so 'My Image.jpg' becomes 'my-image'. // This is tricky. // BETTER APPROACH: // Just match by 'post_name' (slug) being similar to filename-without-extension. // OR: 'guid' ending in filename. $count = 0; $fbv_rel_table = $wpdb->prefix . 'fbv_attachment_folder'; foreach ($filenames as $filename) { // Sanitize filename to potential post_name $name_part = pathinfo($filename, PATHINFO_FILENAME); $sanitized = sanitize_title($name_part); // Find attachment created today with this name // We use LIKE because WP might append -1, -2 if duplicate $attachment = $wpdb->get_row( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_date LIKE %s AND (post_title = %s OR post_name = %s) ORDER BY ID DESC LIMIT 1", '2026-02-14%', $name_part, $sanitized )); if ($attachment) { $att_id = $attachment->ID; // Assign to folder $exists = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $fbv_rel_table WHERE attachment_id = %d", $att_id) ); if (!$exists) { $wpdb->insert( $fbv_rel_table, array( 'folder_id' => $fbv_folder_id, 'attachment_id' => $att_id ) ); // echo "Assigned $filename (ID: $att_id)\n"; $count++; } } } echo "Successfully assigned $count images to folder 'quienes_somos' (ID: $fbv_folder_id).\n"; ?>