Skip to content

Instantly share code, notes, and snippets.

@agroff
Created December 4, 2013 18:23
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save agroff/7792751 to your computer and use it in GitHub Desktop.
Adds files to wordpress' database if they exist in the upload path but are not currently registered.
function prefix_get_in_db($docRoot, $url)
{
$filesInDb = array();
$query_images_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$query_images = new WP_Query($query_images_args);
foreach ($query_images->posts as $post)
{
$foundUrl = wp_get_attachment_url($post->ID, "full");
$filesInDb[] = str_replace($url, $docRoot, $foundUrl);
}
return $filesInDb;
}
function prefix_get_in_filesystem($docRoot)
{
$filesInFs = array();
$isThumbnail = '/\d+x\d+\.[a-zA-Z]+$/';
$path = realpath($docRoot . '/wp-content/uploads');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach ($objects as $path => $info)
{
$name = $info->getFilename();
if(!$info->isFile())
{
continue;
}
if(preg_match($isThumbnail, $name) === 1)
{
continue;
}
$filesInFs[] = $path;
}
return $filesInFs;
}
function prefix_add_file($file)
{
$attachment = array(
"post_title" => array_pop(explode(DIRECTORY_SEPARATOR, $file)),
"post_content" => "",
"post_status" => "inherit",
"post_type" => "attachment",
"guid" => str_replace(" ", "", $file),
"post_mime_type" => mime_content_type($file)
);
wp_insert_attachment( $attachment, $file);
}
$docRoot = $_SERVER["DOCUMENT_ROOT"];
$url = get_site_url();
$filesInDb = prefix_get_in_db($docRoot, $url);
$filesOnFs = prefix_get_in_filesystem($docRoot);
foreach($filesOnFs as $file)
{
if(!in_array($file, $filesInDb))
{
echo "Adding file: $file <br />";
prefix_add_file($file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment