前言
有时候我们删除掉没有用的文章,而文章中的特色图片以及文章内容中的图片没有删除,久而久之容易占用服务器资源空间,有一段代码可以在删除文章的同时把文章中的图片删除!
使用教程:
在启用的主题中的functions.php文件中加入以下代码,加入前可以先备份一下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');