Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Adds files to wordpress' database if they exist in the upload path but are not currently registered.

View functions.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
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
Something went wrong with that request. Please try again.