How to Make WordPress Remove Image Content When Deleting a Post: Detailed Solution

Webmasters who use WordPress will definitely have an experience. Every time they publish an article for illustration, it will automatically generate a folder corresponding to the date in the program directory based on the date. The longer the time, the more directories will be generated. Moreover, the server configuration used by each webmaster is different. If your server is small, if you directly delete files but cannot clean up the images attached to the article in time, many images will be lost on the disk. , resulting in many unnecessary image files stored in WordPress.

The following are collected on the Internet and can be used to delete WordPress image features and image attachments when deleting files. You can split the code or use it all according to your needs.

 
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

/* Delete image attachments when deleting an article*/  
function delete_post_and_attachments($post_ID) {  
        global $wpdb;  
        //Delete featured images  
        $thumbnails = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );  
        foreach ( $thumbnails as $thumbnail ) {  
        wp_delete_attachment( $thumbnail->meta_value, true );  
        }  
        //Delete image attachments  
        $attachments = $wpdb->get_results( "SELECT * FROM $wpdb- >posts WHERE post_parent = $post_ID AND post_type = 'attachment'" );  
        foreach ( $attachments as $attachment ) {  
        wp_delete_attachment( $attachment->ID, true );  
        }  
        $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );  
}  
add_action('before_delete_post', 'delete_post_and_attachments');

Instructions

Place the above code below the theme functions.php file <?php code to add it successfully.

Precautions

When you delete an article, you first execute the function content to delete the featured image and image attachments. However, if you use action delete_post instead of before_delete_post, the media attachment will not be deleted correctly after the article is deleted because the association between the media attachment and the article has been cancelled.

Guess you like

Origin blog.csdn.net/winkexin/article/details/131761309