WordPress删除文章时同时删除图片附件

Wordpress删除文章时同时删除图片附件

为节省服务器空间便于wordpress的图片附件管理,可以在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');
温馨提示:本文最后更新于2021-10-10 15:47:23,某些文章具有时效性,若有错误或已失效,请在下方留言或联系游熊
© 版权声明
THE END
喜欢就支持一下吧
点赞21
分享
评论 抢沙发
游熊的头像-有熊生活

昵称

取消
昵称表情代码图片