Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaemnnosttv/88615e44ef43e911ad15 to your computer and use it in GitHub Desktop.
Save aaemnnosttv/88615e44ef43e911ad15 to your computer and use it in GitHub Desktop.
AS3CF - Upload all missing media library items to S3
<?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