wordpress删除文章时自动删除文章图片

WordPress删除文章时候文章的图片和略缩图源文件并不会从服务器删除,对于强迫症来说这太难受了,去网上搜索了一下,有相关的教程,下面的代码放到主题的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'); 
/* 删除文章时删除图片附件over */

测试代码的方法:新建一个文章,添加一张图片,然后再后台删除,看看图片是否已经自带被删除即可。

© 版权声明
THE END
喜欢就支持以下吧
点赞1
分享
评论 抢沙发