Ran into an interesting bug today on the Motherblog plugin. Despite being in use for a number of years this is the first time we’ve run into this particular issue.
It seemed that if a student was using their blog for two different courses and the two courses used identical subcategories for assignments the subcategories would not be created on the student blog.
So if class A did something like
[altlab-motherblog category="ClassA" sub_categories="Blog 1, Blog 2, Blog 3"]
And class B did
[altlab-motherblog category="ClassB" sub_categories="Blog 1, Blog 2, Blog 3"]
Then whichever one went first would work fine but the second one would only duplicate the parent category.
This plugin was written by Mark Luetke who’s been gone for a long time now. It’s often not easy to debug my own work and it’s harder to parse out someone else’s work. After a bit of scanning I did find the following function. Note that it’s named something sensible which made it much easier to find.
function create_sub_categories($string, $category){ if ($string){ $string = str_replace(' ', '', $string); $array = explode(',',$string); foreach( $array as $item ){ $the_sub_category = get_term_by('name', $item, 'category'); if( !$the_sub_category){ $args = array( 'parent' => $category->term_id, ); wp_insert_term( $item, 'category', $args ); } } } }
The key component ended up being the catch that looks for duplicates.
$the_sub_category = get_term_by('name', $item, 'category');
There’s no way I saw to modify this to check for the parent ID first. The plugin just asks if the term exists and then if it doesn’t — !$the_sub_category — it makes the subcategory. Our problem was that the term did exist but we wanted the extra step to see that if the term did exist was it a child of the parent category. Turns out that that get_term_by does return the parent ID so we can add an OR statement that says make the subcategories if they don’t exist or if their parent doesn’t equal the parent category that we’ve just made.
That looks like the piece below. Just a tiny modification.
function create_sub_categories($string, $category){ if ($string){ $string = str_replace(' ', '', $string); $array = explode(',',$string); foreach( $array as $item ){ $the_sub_category = get_term_by('name', $item, 'category'); if( !$the_sub_category || (int)$the_sub_category->parent != (int)$category->term_id ){ //expanded if statement to deal with duplicate sub cats on destination blog $args = array( 'parent' => $category->term_id, ); wp_insert_term( $item, 'category', $args ); } } } }