時間: 2017-11-18 22:43 來源: 本站整理
分享到:
今天小編整理一篇wordpress 4.4.1刪除文章同時刪除圖片附件以及特色圖像方法的文章和大家分享,希望能給大家提供幫助!
WordPress在刪除文章時,文章內所上傳到媒體庫的圖片等附件不會自動刪除,時間久了之后占用了網站空間,備份網站文件也不劃算。以下的代碼可以實現在刪除文章時自動刪除文章圖片附件以及特色圖片,將代碼放到當前主題inc/fn.php(wordpress 4.4.1版本),如果是老版本則修改functions.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’);
wordpress 4.4.1刪除文章同時刪除圖片附件以及特色圖像方法的文章和大家分享結束,感謝閱讀!
(責任編輯:大衛)分享到: