乐于分享
好资源不私藏

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');

 

 

未经允许不得转载:9i资源网 » WordPress-删除文章时会同时删除图片附件代码

评论 抢沙发

评论前必须登录!

立即登录   注册

×
订阅图标按钮