Last active
September 19, 2017 11:32
-
-
Save sabrina-zeidan/1fb81fda0e28dfeb67b4036077e40af5 to your computer and use it in GitHub Desktop.
Clean uploads directory from unused images. Part 1: Define all images used by all custom post type's and combine them into list. Part 2: Dekete all images from wp-content/uploads that are not in list [WordPress]
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
$args = array( 'post_type' =>'post', 'posts_per_page' => -1, 'post_status' => 'any', 'fields' =>'ids'); | |
$myposts = get_posts( $args ); | |
$all_bookcovers_posts = array(); | |
foreach ($myposts as $mypostid) { | |
$bookcover = get_field('bookcover', $mypostid); | |
$all_bookcovers_posts[] = $bookcover; | |
} | |
$args = array( 'post_type' =>'book_list', 'posts_per_page' => -1, 'post_status' => 'any', 'fields' =>'ids'); | |
$myposts = get_posts( $args ); | |
$all_bookcovers_book_lists = array(); | |
foreach ($myposts as $mypostid) { | |
$book_list_pictrue = get_field('book_list_pictrue', $mypostid); | |
$all_bookcovers_book_lists[] = $book_list_pictrue; | |
} | |
$args = array( 'post_type' =>'bookauthor', 'posts_per_page' => -1, 'post_status' => 'any', 'fields' =>'ids'); | |
$myposts = get_posts( $args ); | |
$all_bookcovers_bookauthors = array(); | |
foreach ($myposts as $mypostid) { | |
$bookauthor_picture = get_field('bookauthor_picture', $mypostid); | |
$all_bookcovers_bookauthors[] = $bookauthor_picture; | |
} | |
$all_good_pictures = array_merge($all_bookcovers_book_lists, $all_bookcovers_bookauthors, $all_bookcovers_posts); | |
$all_good_pictures = array_filter($all_good_pictures); |
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
//Look through wp-content/uploads directory | |
$uploads_dir = wp_upload_dir(); | |
$search = $uploads_dir['basedir']; | |
$replace = $uploads_dir['baseurl']; | |
$uploads_dir = ( $uploads_dir['basedir']); | |
$root = $uploads_dir; | |
//Going through directiry recursevely | |
$iter = new RecursiveIteratorIterator( | |
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS), | |
RecursiveIteratorIterator::SELF_FIRST, | |
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied" | |
); | |
foreach ($iter as $fileinfo) { | |
if ($fileinfo->isFile()) { | |
$image = $fileinfo->getPathname(); | |
$image_url = str_replace($search, $replace, $image); | |
//Delete if file is not found in list of good images | |
if (!in_array($image_url, $all_good_pictures)) { | |
unlink($image); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment