metrofeed
Member
Posted 7 months ago #
I recently did a Drupal to WordPress conversion, which went surprisingly smoothly with one exception. My wordpress now has 36k categories, of which 25k are not being used. This is causing memory issues and other problems with the site.
I am looking for a way to delete every category that doesn't have any posts associated with it. Any ideas?
make a backup of your database first.
Put this in your theme's page template file page.php:
<?php
$categories = get_categories('hide_empty=0');
foreach ( $categories as $category ) {
if($category->count == 0) {
wp_delete_category( $category->cat_ID);
}
}
?>
and load a page once.
metrofeed
Member
Posted 7 months ago #
Cool. That's a great idea. I will give that a try and post on how it works.
metrofeed
Member
Posted 7 months ago #
Unfortunately this isn't working because of the sheer volume of categories. I've got system memory up to 128MB and it's still causing a memory timeout. Any other ideas?
Try it 50 at a time:
<?php
$categories = get_categories('hide_empty=0&number=50');
foreach ( $categories as $category ) {
if($category->count == 0) {
wp_delete_category( $category->cat_ID);
}
}
?>
Keep refreshing the page until you're done
metrofeed
Member
Posted 7 months ago #
Great suggestion! This is now allowing the page to fully load, no memory timeouts. The first round deleted only 11 categories though, so I'm wondering what else might be going on. Either there's something in the syntax that isn't quite right, or... I don't know. When I look at the categories in WordPress Admin, I clearly see tons and tons with zero posts, yet those aren't being deleted by this function even though the function appears to be running. Hmm.
Keep refreshing the page until you're done
maybe increase the number to 500 or some other number:
$categories = get_categories('hide_empty=0&number=500');
metrofeed
Member
Posted 7 months ago #
I wanted to let you know that this worked! Now I have to work on the categories with >2 post, as I still have a ton of useless categories!