图文并茂一直是小编认为的网站文章的基本要求,一篇好的文章离不开生动的文字与适当的图片,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’);