用代碼讓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]