Hack: Removing a Category From Multiple Posts

I recently decided to split up a category. I had a general “posts” category that represented all non-video text posts. I sometimes posted special features or commentary under this category. And recently I’ve been posting news. So I created a “news” category and added that to all of the news posts.

Now I wanted to remove the”posts” category from all of the posts that I had added “news” to. But there were 60 of them. So doing it manually was a bit of a pain. And what if there were 600? Seems a script may be better.

So I wrote a one-time use script and put it in a plain PHP file in a temporary directory on my site. Here is the script:

include('../wp-config.php');
wp('');
$posts = get_posts(array('posts_per_page' => -1));
foreach ($posts as $post) {
	setup_postdata($post);
	if ((in_category('news')) && (in_category('posts'))) {
		echo($post->post_title.'<br>');
		wp_remove_object_terms($post->ID, 'posts', 'category');
	}
}

So the first two lines grab all of the WordPress stuff, so I have access to the WordPress functions. Then I get all of the posts. The loop then looks to see which posts have both categories assigned. I didn’t want one or the other, I wanted and. So I made two calls to in_category.

For good measure, I echo the post titles so I can see what it is doing. Then I use wp_remove_object_terms to get rid of the posts category.

When the script was done, I removed it from the server, saving a version on my local drive for future reference.

Much tidier than installing and entire plug-in, learning it, and remembering to remove it.

Leave a Reply

Your email address will not be published. Required fields are marked *