免去手動刪除文章中的無用圖片的煩惱,刪除文章后,還需要在回收站中清除才可生效
一些wordpress用戶在刪除文章時,為了節省服務器空間,還需要一個個的手動刪除文章中的圖片,很是繁瑣,那么下面這些代碼即可幫助到你,大大提供你的寫文效率。
- 代碼來源:詳情
免去手動刪除文章中的無用圖片的煩惱,刪除文章后,還需要在回收站中清除才可生效。
在主題的functions.php
文件中的<?php
下添加以下代碼:
function delete_post_and_attachments($post_ID) {
global $wpdb;
//刪除特色圖片
$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 );
}
//刪除圖片附件
$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');