| | 228 | |
| | 229 | function set_default_category() { |
| | 230 | global $wpdb; |
| | 231 | |
| | 232 | $default_cat_id = (int) get_option('default_category'); |
| | 233 | |
| | 234 | if ( !$default_cat_id ) |
| | 235 | return; |
| | 236 | |
| | 237 | $default_cat = get_term_by('term_id', $default_cat_id, 'category'); |
| | 238 | $tt_ids = array($default_cat->term_taxonomy_id); |
| | 239 | $terms = array($default_cat->term_id); |
| | 240 | |
| | 241 | # mass fetch ids |
| | 242 | $post_ids = $wpdb->get_results(" |
| | 243 | SELECT posts.ID |
| | 244 | FROM $wpdb->posts as posts |
| | 245 | LEFT JOIN $wpdb->term_relationships as term_relationships |
| | 246 | ON term_relationships.object_id = posts.ID |
| | 247 | AND term_relationships.term_taxonomy_id = $default_cat->term_taxonomy_id |
| | 248 | WHERE post_type = 'post' |
| | 249 | AND term_relationships.object_id IS NULL |
| | 250 | "); |
| | 251 | |
| | 252 | # mass insert relationships |
| | 253 | $wpdb->query(" |
| | 254 | INSERT INTO $wpdb->term_relationships ( object_id, term_taxonomy_id ) |
| | 255 | SELECT posts.ID, $default_cat->term_taxonomy_id |
| | 256 | FROM $wpdb->posts as posts |
| | 257 | LEFT JOIN $wpdb->term_relationships as term_relationships |
| | 258 | ON term_relationships.object_id = posts.ID |
| | 259 | AND term_relationships.term_taxonomy_id = $default_cat->term_taxonomy_id |
| | 260 | WHERE posts.post_type = 'post' |
| | 261 | AND term_relationships.object_id IS NULL |
| | 262 | "); |
| | 263 | |
| | 264 | # update count in one go |
| | 265 | wp_update_term_count_now($tt_ids, 'category'); |
| | 266 | |
| | 267 | # mass do_action |
| | 268 | foreach ( $post_ids as $object_id ) { |
| | 269 | do_action('set_object_terms', $object_id, $terms, $tt_ids, 'category', false); |
| | 270 | } |
| | 271 | |
| | 272 | echo __('Set default category on orphaned posts.') |
| | 273 | } |