Skip to content

Instantly share code, notes, and snippets.

@stevenroh
Created September 3, 2019 15:05
Show Gist options
  • Save stevenroh/95ade4db3ca45be497a72926647b7454 to your computer and use it in GitHub Desktop.
Save stevenroh/95ade4db3ca45be497a72926647b7454 to your computer and use it in GitHub Desktop.
WordPress import media from wp_content/uploads
/* Import media present on the wp_uploads folder */
// https://codex.wordpress.org/Function_Reference/wp_insert_attachment
if($_GET['rohs_run']) {
echo 'RUN';
// Get WP uploads dir
$wp_upload_dir = wp_upload_dir();
// Init recursive Obj
$di = new RecursiveDirectoryIterator($wp_upload_dir['path'], RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
// get filetype for attachment meta
$filetype = wp_check_filetype( $file->getPathname(), null );
// attachment meta
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . $filename,
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename );
// echo $attach_id;
}
}
@stevenroh
Copy link
Author

Don't forget to change max exec time and default_socket_timeout

@stevenroh
Copy link
Author

Some useful commands

DELETE FROM $posts WHERE post_type = 'attachment' AND guid LIKE '%uploads/products%'
DELETE FROM $posts WHERE post_type = 'attachment' AND guid LIKE '%wc-logs%'
DELETE FROM $posts WHERE post_type = 'attachment' AND guid LIKE '%thumb%'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment