用代码让WordPress删除文章时,把媒体库图片和缩略图一起删除

我们要将一篇文章删除时,希望可以删除比较彻底。
那么媒体库里面的图片、以及自动生成的缩图。可以一起删除
可以用以下代码,开启主题的functions.php
[cc lang="php"] //用代碼讓WordPress刪除文章時,把媒體庫圖片和縮略圖一起刪除 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’);[/cc]

评论 (0)

此处尚未发表评论

留言

  1. 以游客身份发表评论。注册登入到您的帐户。
附件 (0/ 3)
分享您的位置