功能实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//删除文章时删除图片附件 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'); |
将上述代码放到主题functions.php文件<?php代码的下面即可添加成功,并在主题上运行了。
当你在删除文章时先执行函数内容,删除特色图片以及图片附件,但是如果在使用action delete_post而不是before_delete_post将导致删除文章后因媒体附件与文章关联已取消而无法正确删除。
文章评论
挺好的,感谢博主的分享。