WordPress删除文章时,文章的图像和缩略图源文件不会从服务器中删除。这对强迫症来说太难了。我在网上搜索。有相关的教程。以下代码可以放在主题的functions.php文件中。
function delete_post_and_attachments($post_ID) {
$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’);
测试代码的方法:新建一个文章,添加一张图片,然后再后台删除,看看图片是否已经自带被删除即可。