WordPress如何在删除文章时自动删除文章内的图片

前言:

WordPress在删除文章后图片不会自动删除,造成了储存资源的浪费,并且也使Wordpress越来越浮肿,影响网站运行速度。

教程:

将下面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
喜欢就支持一下吧
点赞37赞赏 分享
评论 抢沙发
头像
拿起笔,写下你的梦想,你的人生就从此刻起航
提交
头像

昵称

取消
昵称表情代码图片