admin管理员组文章数量:1122832
On my site I have multiple authors, who can add/edit/delete custom posts and upload (attach) images to those posts. The problem is - when they delete their posts, attachments stay on the server. So, I would like to get rid of all files attached to the post when it gets deleted. Can anyone share and example how it's done?
On my site I have multiple authors, who can add/edit/delete custom posts and upload (attach) images to those posts. The problem is - when they delete their posts, attachments stay on the server. So, I would like to get rid of all files attached to the post when it gets deleted. Can anyone share and example how it's done?
Share Improve this question asked Jun 26, 2011 at 19:09 KovasKovas 4332 gold badges7 silver badges16 bronze badges4 Answers
Reset to default 4WP does not do this by default since there is no guarantee that attachment isn't still being used by some other post.
Basic logic would be to hook into delete_post
, query for child attachments and run wp_delete_attachment()
on each.
I did quick search in plugin repository and came up with tiny plugin that does just that (seems unmaintained so test before use) - Post Data Delete Advanced.
I wrote the following function that uses the logic suggested by @rarst in his answer.
add_action( 'before_delete_post', function( $id ) {
$attachments = get_attached_media( '', $id );
foreach ($attachments as $attachment) {
wp_delete_attachment( $attachment->ID, 'true' );
}
} );
IMPORTANT: Keep in mind it will only be called when the posts are permanently deleted from the trash! If you want to change this behaviour, include the following line in your wp-config.php
file:
define('EMPTY_TRASH_DAYS', 0);
If this constant is set to 0, the trash functionality will be disabled and the 'Delete Permanently' button will appear instead of 'Trash' button. If you click 'Delete Permanently' button, the item will immediately be deleted without any alert message.
(From the Codex)
Expanding on other answers here for use with only a specific post type.
add_action( 'before_delete_post', 'delete_all_attached_media' );
function delete_all_attached_media( $post_id ) {
if( get_post_type($post_id) == "post" ) {
$attachments = get_attached_media( '', $post_id );
foreach ($attachments as $attachment) {
wp_delete_attachment( $attachment->ID, 'true' );
}
}
}
This will delete all attached media when a post is permanently deleted.
Any one still looking for a simple solution then try the following plugin it works with normal post/page, and custom post types - Delete Post with Attachments
本文标签: attachmentsDelete post with all files attached to it
版权声明:本文标题:attachments - Delete post with all files attached to it 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736308638a1933735.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论