Last active
August 11, 2017 03:08
-
-
Save chasecmiller/4aa7133824dbc99c4700a0570d40d5fd to your computer and use it in GitHub Desktop.
Move WordPress pre-existing attachments to S3 using WP Offload S3 Lite.
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 | |
/** | |
* You can include this snippet anywhere. | |
* Just remove the reference once you're done. | |
* It checks to make sure files exist and are readable. | |
* | |
* If WP Offload S3 Lite is not installed, this won't do anything other than waste resources. | |
* | |
* Love the full plugin? Buy it! | |
**/ | |
add_action('aws_init', | |
function ($aws) { | |
global $wpdb; | |
$ids = $wpdb->get_col('SELECT ID FROM '.$wpdb->posts.' WHERE post_type="attachment" AND ID NOT IN (SELECT post_id FROM '.$wpdb->postmeta.' WHERE meta_key="amazonS3_info") ORDER BY RAND() LIMIT 5000'); | |
$i = 0; | |
foreach ($ids as $id) { | |
$data = wp_get_attachment_metadata($id); | |
if (!is_array($data)) { | |
$data = json_decode($data, true); | |
} | |
$file = WP_CONTENT_DIR . '/uploads/' . $data['file']; | |
if ( | |
!file_exists($file) | |
|| | |
!is_file($file) | |
|| | |
!is_readable($file) | |
|| | |
is_dir($file) | |
) { | |
continue; | |
} | |
wp_update_attachment_metadata($id, $data); | |
$i++; | |
} | |
} | |
, 99, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment