WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Im trying to check if 'categoryone' has a parent. Right know I can check and see that there is a category called categoryone, but I want to check categoryone for parent and child categories. I have tried to code something like the code bellow. Finaly my goal is to use wp_set_post_categorie(); after the category check.

 foreach ( $network_posts as $network_post ) {

  // Add the new post
  $insert_id = wp_insert_post( $network_post->post );

  // Add metadata (useful for lookups later)
  update_post_meta( $insert_id, '_network_content', 1 );
  update_post_meta( $insert_id, '_network_site_orig_id', array(
'site_id' => $bid,
'post_id' => $network_post->id,
 ) );

 $tid = term_exists('categoryone', 'category', 0);

 $term_ids = [];

 if ( $tid !== 0 && $tid !== null )
  $term_ids[] = $tid['term_id'];

  $insert_term_id = wp_insert_term( 'categoryone', 'category' );
  if ( ! is_wp_error )
  $term_ids[] = $insert_term_id;
  wp_set_post_categories( $insert_id, $term_ids );
share|improve this question

First of all consider that if the category exists, term_exists function return an array, not a term id. See Codex.


$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

share|improve this answer
Hi, I have changed my code a little bit, and know I wonder how to use $insert_id with wp_set_post_categories();. – LoveWP Sep 29 '13 at 8:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.