Adds files to wordpress' database if they exist in the upload path but are not currently registered.
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
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