对自己要求过高的wp站长总会喜欢删除文章,删除后文章内的图片还会遗留在服务器内。不仅后期整理图片不方便,而且当你搬家时,想清理清理图片目录,会发现不知道哪个是不用的! 文章都删了,我还要图片干嘛??不爱了就是不爱了!!为什么还留在我的服务器内?!!
删除文章同时,删除文章内图片的方法就这样来了!
使用方法:
放在主题目录的function.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');
// 结束