逐梦论坛's Archiver

shillan 发表于 2015-6-30 00:54

WordPress删除文章同时自动删除缩略图及图片附件

[p=30, 2, left]WordPress删除文章时,文章内所上传到[url=http://www.zhiyanblog.com/tag/%e5%aa%92%e4%bd%93%e5%ba%93]媒体库[/url]的图片等附件不会自动删除,占用了网站空间,因此下面说明通过几行代码的简单方式实现在删除文章时自动删除[url=http://www.zhiyanblog.com/tag/%e7%bc%a9%e7%95%a5%e5%9b%be]缩略图[/url]以及图片附件,这样就不用手动去[url=http://www.zhiyanblog.com/tag/%e5%aa%92%e4%bd%93%e5%ba%93]媒体库[/url]寻找并删除,准确而且效率高。[/p]代码[list=1][*]/* 删除文章时删除图片附件[*]/* ------------------------ */[*]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');[/list]
说明[p=30, 2, left]将上述代码放到主题functions.php文件中即可使用,其在删除文章时先执行函数内容,删除特色图片以及图片附件,如果在使用action delete_post而不是before_delete_post将导致删除文章后因媒体附件与文章关联已取消而无法正确删除。[/p]

页: [1]

Powered by Discuz! Archiver 7.2  © 2001-2009 Comsenz Inc.