I’ve been writing a custom WordPress plugin to accept emailed posts and insert them into a WordPress blog. One of the difficult issues I’ve encountered is that WordPress deals with tags and categories in different ways: it’s relatively easy to add and remove tags. It takes a bit of roundabout work to do the same with categories.
The below code fragment takes a string array of categories ( $to_post_categories ) and sets them onto a post (the ID of the post is in $created_post_id ).
//Set post categories
/**
* WP doesn't allow us to set categories as easily as tags. With tags we can simply declare
* the names of the tags and be done with it. WP requires that we pass in the ID of the category,
* and if the category doesn't exist, we need to create it. So we loop through the array of
* category names, see if they exist (and if so, collect the ID) and if they don't exist,
* create the category and map the ID to the post.
**/
foreach ($to_post_categories as $category_name) {
$category_id = get_category_by_slug($category_name);
if ($category_id == false) {
//Category doesn't exist, create it
$category_id = wp_create_category($category_name);
}
//category_id now holds ID of right category or recently created category.
//Add category to post
wp_set_post_categories($created_post_id, array($category_id), true);
}//end looping through post categories sent to us