[Info] PHP Code/Program to Delete Unused Images in WordPress || 워드프레스 사용하지 않는 이미지 삭제 PHP 코드/프로그램
This post was written on December 19, 2023

[English]

★ Assumes no responsibility for the use of this program/code. ★
This code/program is designed to delete unused images in WordPress. Simply place the code inside a folder at the WordPress root directory. Used images are displayed in blue, unused in gray. Deletion can be done using checkboxes. It is strongly recommended to back up all images before proceeding.
※ Images in unpublished posts are treated as unused.
※ This approach involves removing all unused images, which is not the preferred method.
※ Depending on how you use WordPress, there can be various side effects. It is essential to back up the ‘uploads’ folder before proceeding.
※ As this program/code is easily exposed externally, it is recommended to change the file name when using it.
※ If you wish to use this code without PHP knowledge, please email pwc_h@naver.com.
※ This code was created by chatGPT. it’s fantastic
Download PHP Code/Program

WordPress automatically saves one image in multiple sizes, resulting in inefficient use of storage space. While plugins can address this issue, many are paid and difficult to use. If you back up regularly, you can efficiently manage storage space with this program/code. If it works well, be sure to leave a comment. This code was created 100% by ChatGPT, but it took a very long time for ChatGPT to figure out how to create this program/code.

[Korean]

★ 본 프로그램/코드의 사용에 어떤 책임도 지지 않는다. ★
워드프레스에서 사용하지 않는 이미지를 삭제하는 코드/프로그램이다. wordpress 최상위 레벨의 폴더 안에 넣으면 되고, 사용되는 이미지는 파란색 폰트로, 사용되지 않는 이미지는 회색 폰트로 나타난다. 체크박스를 이용하여 삭제할 수 있도록 설계했다. 반드시 모든 이미지를 백업한 뒤에 사용할 것을 권장한다.
※ 공개된 포스트가 아닌 포스트에 있는 이미지는 사용되지 않는 이미지로 간주된다.
※ 간혹, 한글로 된 파일명을 가진 이미지 파일은 사용 유무와 관계없이 제거될 때가 있다.(모두 그런 것은 아니다.)
※ 이 방식은 사용하지 않는 모든 이미지를 제거하는 방식으로, 워드프레스가 좋아하는 방식이 아니다.
※ 외부에 쉽게 노출되는 방식의 프로그램/코드이므로 되도록 파일명을 바꿔서 사용하는 것을 권장한다.
※ 당신이 워드프레스를 사용하는 방식에 따라서, 다양한 부작용이 있을 수 있다. 반드시 uploads 폴더를 백업한 뒤에 진행해야 한다.
※ PHP 지식이 없는 상황에서, 본 코드 사용을 원한다면, pwc_h@naver.com 으로 메일을.
※ chatGPT가 만든 코드이다. 정말 환상적이다.
다운로드 PHP 코드/프로그램

워드프레스는 하나의 이미지를 여러 사이즈로 자동 저장한다. 저장 공간을 비효율적으로 사용한다. 플러그인을 통해 보완할 수 있지만, 대부분 유료이고, 사용 방법이 어렵다. 백업만 잘 한다면 본 프로그램/코드를 통해 저장 공간을 효율적으로 사용할 수 있다. 잘 사용했다면, 댓글은 무조건 남겨줘야 한다. 이 코드는 100% chatGPT가 만들었지만, chatGPT가 이 프로그램/코드를 만들 수 있게 꼬시는 것에는 매우 오랜 시간이 걸렸다.

원본이 삭제될 경우 지원되지 않을 수 있습니다.

<?php
// Set the path for the uploads folder. (업로드 폴더의 경로 설정.)
require_once('wp-load.php');
// Number of images to display per page. (한 페이지에 표시할 이미지 개수.)
$uploads_dir = wp_upload_dir()['basedir'];
$images_per_page = 1000;
// Get the current page. (현재 페이지 가져오기.)
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
// Get a list of all image files. (모든 이미지 파일 목록 가져오기.)
$all_images = glob($uploads_dir . '/*/*/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
// Get all posts. (모든 포스트 가져오기.)
$args = array(
    'post_type' => array('post', 'page'), // Search for both posts and pages. (포스트와 페이지 모두 검색.)
    'posts_per_page' => -1,
);
$posts = get_posts($args);
// Get all pages. (모든 페이지 가져오기.)
$pages = get_pages(array('sort_column' => 'post_date', 'sort_order' => 'desc'));
// Combine posts and pages. (포스트와 페이지 결합.)
$all_posts = array_merge($posts, $pages);
// Crop the list of visible images based on the current page. (현재 페이지에 맞게 이미지 리스트 자르기.)
$start_index = ($current_page - 1) * $images_per_page;
$visible_images = array_slice($all_images, $start_index, $images_per_page);
// Image deletion handling. (이미지 삭제 처리.)
if (isset($_POST['delete_images'])) {
    $selected_images = $_POST['delete_images'];
    foreach ($selected_images as $selected_image) {
        // Delete the image file. (이미지 파일 삭제.)
        unlink($uploads_dir . $selected_image);
    }
    // Reload the page. (페이지 리로드.)
    echo '<meta http-equiv="refresh" content="0"/>';
}
// Output: Image list (출력: 이미지 목록)
echo '<h1>Image List (이미지 목록)</h1>';
echo '<form method="post">';
echo '<ul>';
foreach ($visible_images as $image) {
    // Extract the relative path of the image file. (이미지 파일의 상대 경로 추출.)
    $relative_path = str_replace($uploads_dir, '', $image);
    // Extract only the image file name. (이미지 파일명만 추출.)
    $image_name = pathinfo($image, PATHINFO_BASENAME);
    // Check if the image file has been used in any post or page. 
    // (해당 이미지 파일이 포스트 또는 페이지에서 사용되었는지 확인.)
    $is_used = false;
    foreach ($all_posts as $post) {
        // Get post content. (포스트 내용 가져오기.)
        $content = $post->post_content;
        // Check if the image file name exists in the post content. 
        // (이미지 파일명이 포스트 내용에 존재하는지 확인.)
        if (strpos($content, $image_name) !== false) {
            $is_used = true;
            break;
        }
    }
    // Output and specify color. (출력 및 컬러 지정.)
    $color = $is_used ? 'blue' : 'black';
    // Set default checkbox state to checked only for images that are not in use. 
    // (이미지가 사용되지 않은 경우에만 체크박스 기본 체크 상태로 설정.)
    $checked = !$is_used ? 'checked' : '';
    echo '<li style="color: ' . $color . ';">' . $image_name . ' - ' . $relative_path . ' ';
    echo '<input type="checkbox" name="delete_images[]" value="' . $relative_path . '" ' . $checked . '/></li>';
}
echo '</ul>';
// Output delete button and pagination bar. (삭제 버튼 및 페이징바 출력.)
echo '<input type="submit" value="Delete Selected Images(선택한 이미지 삭제)"/>';
echo '</form>';
echo '<div class="pagination">';
for ($i = 1; $i <= ceil(count($all_images) / $images_per_page); $i++) {
    echo '<a href="?page=' . $i . '">' . $i . '</a>';
}
echo '</div>';
?>

[English]
Although the specifics may elude me, it seems ChatGPT has ushered in a new era. Quite remarkable.

[Korean]
정확히 얼만큼인지 어디인지는 몰라도, chatGPT가 새로운 세상을 연 것은 맞는 것 같다. 대단하다.




HS LOG List of ETC

Copyright © HS LOG

No Comments

Thank you for visiting. If you leave a comment, I will not forget.

HS LOG List of ETC

 
The number of visitors for this post is 216 (measured by Jetpack).