Make WordPress Core

Ticket #3460: add_to_default_cat_posts_that_only_exist_in_deleted_cat.diff

File add_to_default_cat_posts_that_only_exist_in_deleted_cat.diff, 2.0 KB (added by markjaquith, 19 years ago)

Patch for 2.0.x

  • wp-admin/admin-db.php

     
    154154        global $wpdb;
    155155
    156156        $cat_ID = (int) $cat_ID;
     157        $default_cat = get_option('default_category');
    157158
    158159        // Don't delete the default cat.
    159160        if ($cat_ID == get_option('default_category'))
     
    164165        $parent = $category->category_parent;
    165166
    166167        // Delete the category.
    167         $wpdb->query("DELETE FROM $wpdb->categories WHERE cat_ID = '$cat_ID'");
     168        if ( !$wpdb->query("DELETE FROM $wpdb->categories WHERE cat_ID = '$cat_ID'") )
     169                return 0;
    168170
    169171        // Update children to point to new parent.
    170172        $wpdb->query("UPDATE $wpdb->categories SET category_parent = '$parent' WHERE category_parent = '$cat_ID'");
    171173
    172         // TODO: Only set categories to general if they're not in another category already
    173         $default_cat = get_option('default_category');
    174         $wpdb->query("UPDATE $wpdb->post2cat SET category_id='$default_cat' WHERE category_id='$cat_ID'");
     174        // Only set posts and links to the default category if they're not in another category already
     175        $posts = $wpdb->get_col("SELECT post_id FROM $wpdb->post2cat WHERE category_id='$cat_ID'");
     176        $only_in_deleted = array();
     177        foreach ( (array) $posts as $post_id ) {
     178                $other_cat_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->post2cat WHERE category_id <> '$cat_ID' AND post_id = '$post_id'");
     179                if ( 0 == $other_cat_count ) // exists only in the to-be-deleted category
     180                        $only_in_deleted[] = $post_id;
     181        }
    175182
     183        if ( $only_in_deleted ) {
     184                $only_in_deleted = implode(',', $only_in_deleted);
     185                $wpdb->query("UPDATE $wpdb->post2cat SET category_id='$default_cat' WHERE category_id='$cat_ID' AND post_id IN($only_in_deleted)");
     186        }
     187
     188        // Now, all remaining posts in $cat_ID should exist in another category, so we can do:
     189        $wpdb->query("DELETE FROM $wpdb->post2cat WHERE category_id='$cat_ID'");
     190
    176191        wp_cache_delete($cat_ID, 'category');
    177192        wp_cache_delete('all_category_ids', 'category');
    178193