Last active
December 2, 2023 00:40
-
-
Save aaemnnosttv/88615e44ef43e911ad15 to your computer and use it in GitHub Desktop.
AS3CF - Upload all missing media library items to S3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* For use with Amazon S3 and CloudFront by Delicious Brains | |
* | |
* Upload this file to your installation and trigger it with WP-CLI: | |
* wp eval-file as3cf-upload-missing-media-library-items-to-s3.php | |
*/ | |
global $as3cf; | |
if (! $as3cf instanceof Amazon_S3_And_CloudFront) { | |
return; | |
} | |
/** | |
* Run the operation in a closure for ecapsulation. | |
*/ | |
call_user_func(static function ($as3cf) { | |
/** | |
* Get all attachment ids that have no amazon S3 meta data. | |
* | |
* @param int $chunk Maximum number of attachments to return. | |
* | |
* @return array attachment_ids | |
*/ | |
$get_attachment_ids_not_on_s3 = function ($chunk) { | |
return (array) get_posts([ | |
'post_type' => 'attachment', | |
'meta_query' => [ | |
'relation' => 'AND', | |
[ | |
'key' => 'amazonS3_info', | |
'compare' => 'NOT EXISTS', | |
], | |
[ | |
'key' => 'amazonS3_upload_error', | |
'compare' => 'NOT EXISTS', | |
] | |
], | |
'posts_per_page' => (int) $chunk, | |
'fields' => 'ids', | |
]); | |
}; | |
$uploaded = 0; | |
$total = 0; | |
while ($attachment_ids = $get_attachment_ids_not_on_s3(100)) : | |
WP_CLI::line('Uploading ' . count($attachment_ids) . ' attachments to S3...'); | |
foreach ($attachment_ids as $attach_id) { | |
$result = $as3cf->upload_attachment_to_s3($attach_id); | |
// Prevent infinite recursion if upload fails. | |
if (is_wp_error($result)) { | |
update_post_meta($attach_id, 'amazonS3_upload_error', $result->get_error_message()); | |
WP_CLI::warning($attach_id . ' - ' . $result->get_error_message()); | |
} else { | |
$uploaded++; | |
WP_CLI::success($attach_id . ' - ' . json_encode($result)); | |
} | |
$total++; | |
} | |
endwhile; | |
WP_CLI::line("Process Complete. Uploaded $uploaded/$total attachments to S3."); | |
}, $as3cf); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment