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

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

027482

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');
/* 删除文章时删除图片附件 over */
© 版权声明
THE END
文章不错?点个赞呗
点赞82赞赏
分享
评论 抢沙发
小语雀的头像-小语雀网

昵称

取消
昵称表情代码图片