Skip to content

Instantly share code, notes, and snippets.

@seangenabe
Last active August 29, 2015 14:02
Show Gist options
  • Save seangenabe/96b48d5520a253f84808 to your computer and use it in GitHub Desktop.
Save seangenabe/96b48d5520a253f84808 to your computer and use it in GitHub Desktop.
Import files uploaded on server to Wordpress
<?php
# If placed in wp-content/uploads
$path_to_wp_blog_header = '../../wp-blog-header.php';
# Directory relative to wp-content/uploads
$dir = 'import';
# Attach to post ID
$post_id = 0;
error_reporting(E_ALL);
include $path_to_wp_blog_header;
$upload_dir = wp_upload_dir();
function import_files_from_directory($dir) {
$files = scandir($dir);
# Linux
$files = array_diff($files, array('.', '..'));
echo 'Importing files from directory: ' . $dir . '<br>';
foreach ($files as $basename) {
$fullname = $dir . '/' . $basename;
if (is_dir($fullname)) {
import_files_from_directory($dir);
}
else {
$filetype = wp_check_filetype($basename, null);
$id = wp_insert_attachment(array(
'guid' => $fullname,
'post_mime_type' => $filetype['type'],
'post_title' => $basename,
'post_content' => '',
'post_status' => 'inherit'
), $fullname, 0);
echo 'Imported file ' . $fullname . ' to media library with ID ' . $id . '<br>';
}
}
unset($basename);
echo '<br>';
}
import_files_from_directory($upload_dir['basedir'] . '/' . $dir);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment