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');
保存更新后,以后删除文章后就不用手工去媒体库寻找图片删除了,是不是很实用!
发表回复