在我们编辑文章时通常会添加一些图片,达成图文混排的效果,但是如果我们遇到删除文章时,文章中的图片并不会一同被删除掉,图片还是会留在服务器中无形中占用了服务器资源,那我们有没有一种办法可以在删除文章的同时将文章中的图片一起删除掉?
只需要将代码添加到当前wordpress主题的Functions.php文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/* 删除文章时删除图片附件 */ 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'); |