Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save conkonig/4cd7f24beb5887c71a2d3cca6b6c2109 to your computer and use it in GitHub Desktop.
Save conkonig/4cd7f24beb5887c71a2d3cca6b6c2109 to your computer and use it in GitHub Desktop.
A plugin for converting WP Site from Humanmade/s3-uploads to deliciousbrains/wp-offload for Media Delivery.
<?php
/*
Plugin Name: WP Attachment Offloader Metadata Migration Plugin
Description: A plugin for converting WP Site from Humanmade/s3-uploads to deliciousbrains/wp-offload for Media Delivery. Not for use in production unless you know what you are doing..!
Version: 1.1
Author: Connor Stansfield + chatgpt
*/
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
if (defined('WP_CLI') && WP_CLI) {
function attachment_migration_command($args, $assoc_args)
{
require_once ABSPATH . 'wp-admin/includes/plugin.php';
if (!is_plugin_active('amazon-s3-and-cloudfront/wordpress-s3.php')) {
WP_CLI::error('Install amazon-s3-and-cloudfront plugin first.');
return;
}
global $wpdb;
// Create a CSV file with the current timestamp
$csv_file = __DIR__ . '/attachment_migration_log_' . date('Y-m-d_H-i-s') . '.csv';
$csv_handle = fopen($csv_file, 'w');
if (!$csv_handle) {
WP_CLI::error("Could not open CSV file for writing: {$csv_file}");
return;
}
// Write CSV header
fputcsv($csv_handle, ['ID', 'Post Title', 'Old URL', 'New URL', 'Status']);
// Query to fetch all attachments from WordPress media library
$query = "SELECT ID, post_title, post_date, guid
FROM {$wpdb->posts}
WHERE post_type = 'attachment'";
$attachments = $wpdb->get_results($query, ARRAY_A);
// If there are attachments, process each one
if ($attachments) {
$total_attachments = count($attachments);
$current_attachment = 0;
WP_CLI::line("Starting migration of {$total_attachments} attachments...");
foreach ($attachments as $attachment) {
$current_attachment++;
// Extract necessary details
$attachment_id = $attachment['ID'];
$attachment_title = $attachment['post_title'];
$attachment_date = $attachment['post_date'];
$old_url = $attachment['guid'];
$attachment_filename = basename($old_url); // Extract filename from URL
$tablename = $wpdb->prefix . "as3cf_items";
$bucket_name = maybe_unserialize(get_option('tantan_wordpress_s3'))['bucket'];
// Construct S3 bucket URL based on your pattern
$bucket_url = "https://$bucket_name.ams3.digitaloceanspaces.com"; // Replace with your S3 bucket URL
$year_month = date('Y/m', strtotime($attachment_date)); // Get year and month from attachment date
// Construct paths
$path = "uploads/{$year_month}/{$attachment_filename}";
$source_path = "{$year_month}/{$attachment_filename}";
$original_source_path = "{$year_month}/{$attachment_filename}";
$new_url = "{$bucket_url}/{$path}";
// Check if the file exists in the bucket
$ch = curl_init($new_url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code != 200) {
$status = 'unprocessed (not found on bucket)';
WP_CLI::warning("Skipped attachment {$current_attachment} of {$total_attachments} - File does not exist in the bucket: {$new_url}");
} else {
$status = 'processed';
// Prepare data to insert into your custom table
$data = array(
'provider' => 'do',
'region' => 'ams3',
'bucket' => $bucket_name, // Replace with your bucket name
'path' => $path,
'original_path' => $path,
'is_private' => 0, // Adjust as necessary
'source_type' => 'media-library',
'source_id' => $attachment_id,
'source_path' => $source_path,
'original_source_path' => $original_source_path,
'extra_info' => '', // You can add additional information if needed
'originator' => 0,
'is_verified' => 1 // Adjust as necessary
);
// Insert data into your custom table
$wpdb->insert($tablename, $data);
WP_CLI::line("Processed attachment {$current_attachment} of {$total_attachments}");
}
// Log to CSV
fputcsv($csv_handle, [$attachment_id, $attachment_title, $old_url, $new_url, $status]);
}
WP_CLI::success("All attachments migrated successfully.");
} else {
WP_CLI::error("No attachments found in the WordPress media library.");
}
// Close the CSV file
fclose($csv_handle);
}
function print_bucketname()
{
require_once ABSPATH . 'wp-admin/includes/plugin.php';
if (!is_plugin_active('amazon-s3-and-cloudfront/wordpress-s3.php')) {
WP_CLI::error('Install amazon-s3-and-cloudfront plugin first.');
return;
}
$bucket_name = maybe_unserialize(get_option('tantan_wordpress_s3'))['bucket'];
WP_CLI::line("Bucket name: $bucket_name");
}
WP_CLI::add_command('attachment-migration migrate_attachments', 'attachment_migration_command');
WP_CLI::add_command('print-bucketname', 'print_bucketname');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment