WordPress删除文章时自动删除图片


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');  
回到顶部