You could make use of WordPress’ get_term_children()
function on the save_post
hook. A nice thing about this is that get_term_children()
is recursive and collapses to a single dimensional array, so if you were to ever add smaller subdivisions as a third, fourth, fifth level, etc – you will automatically grab all hierarchical children with it.
You don’t specifically mention what taxonomy you’re using, but you say Category
in your post. I’ve used the term/taxonomy
functions instead of the category
functions because it lets you adapt easier to custom terms/taxonomies later a bit easier. In this scenario, ideally you’d have a custom taxonomy like “Location” and the terms “Africa, Asia, etc.” would be under that.
This is a bit verbose and is a bit on the “verbose” side to be safe, but it should work to get you started at least:
add_action( 'save_post', 'so_60079535_put_post_in_child_terms', 11 );
function so_60079535_put_post_in_child_terms( $post_id ){
// Get the terms for this post
$taxonomy = 'category';
$terms = wp_get_object_terms( $post_id, $taxonomy );
// If the tax doens't exist, or something fails, abort
if( is_wp_error($terms) )
return;
// If there are none in this tax, abort
if( empty($terms) )
return;
// Loop through terms to find any children, recursively
foreach( $terms as $term ){
$child_terms = get_term_children( $term->term_id, $taxonomy );
//if tax doesn't exist or error, skip this term
if( is_wp_error($child_terms) )
continue;
// If no children, skip this term
if( empty($child_terms) )
continue;
// APPEND these child terms to the parent post object
wp_set_object_terms( $post_id, $child_terms, $taxonomy, true );
}
}