很多时候,我们删除文章的时候,想一并把文章附带的图片、特色图一起删掉,这样会减少系统垃圾,提高网站运行速度,可汗网就为大家分享下可以实现该功能的代码。
将下面的代码放到网站function文件,保存即可。
//删除文章时删除图片附件 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');
注意:1、如果你网站的一张图片链接了很多文章,请谨慎使用该代码;
2、改代码操作就有不可逆性,操作之前请备份好网站数据。