WordPress删除文章时如何自动删除图片以及媒体库中的文件

wordpress的图片以及文章数据都是储存在wp-posts这一个数据表里面的,删除wp-posts表里面的所有媒体文件记录就可以完美解决

DELETE FROM wp_posts WHERE NOT(post_status = 'publish' AND post_type IN('post','nav_menu_item','page'));

ps:wp_posts表中删除文章状态(post_status)不是发布(publish)状态,并且文章类型(post_type)不是文章(post)、导航菜单(nav_menu_item)或者页面(page)的所有文章。

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');
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容