删除文章同时删除图片附件[wordpress开发教程]
一些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');