對于我們在維護 WordPress 內核的網站時候,有些文章可能需要刪除,但是同時文內的圖片和附件還在網站中會占用服務器的空間,最好的辦法肯定是一并刪除。當然,默認如果沒有特殊處理的話,是需要我們單獨的到媒體庫中刪除對應的圖片的。
這里有沒有辦法可以在刪除文章的時候同時自動刪除內容中自帶的附件和圖片。
/* 刪除文章自動刪除文內的圖片和附件 */ 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');
這里將內容添加到當前主題的 Functions.php 文件,需要徹底刪除文章才會被刪除。
評論