First of all consider that if the category exists, term_exists
function return an array, not a term id. See Codex.
So:
$term_ids = array();
$term = term_exists('categoryone', 'category', 0);
if ( is_array($term) && isset($term['term_id']) ) { // term exists as parent cat
$term_ids[] = $term['term_id'];
// get all the children of the categories
$children = get_categories( array( 'parent'=> $term['term_id'], 'hide_empty'=>false) );
if ( ! empty($children) ) {
// category exist as parent and also have children
// do you want to add also the children? If so:
$children_ids = wp_list_pluck($children, 'term_id');
$term_ids = array_merge($term_ids, $children_ids);
} else {
// category exist as parent but has no children
}
} else { // term does not exists as parent cat
$insert_term_id = wp_insert_term( 'categoryone', 'category' );
$term_ids[] = $insert_term_id;
}
And then, if $insert_id
is the ID of a post you can use:
wp_set_post_categories( $insert_id, $term_ids );
For more info see codex for