Php – How to check if a category has a parent category

PHPWordpress

Im trying to check if 'categoryone' has a parent.
Right know I can check and see that there is a category called categoryone, but not if categoryone has a parent category.
I have tried to code something like the code bellow.

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

  $term_ids = [];

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

  }
  else
  {
    // If there is not a parent category!
    $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 );

Best Answer

You may use something like this (Paste this in your functions.php file)

function category_has_parent($catid){
    $category = get_category($catid);
    if ($category->category_parent > 0){
        return true;
    }
    return false;
}

Call this from template

if(category_has_parent($tid)) {
    // it has a parent
}

Check Children

function has_Children($cat_id)
{
    $children = get_terms(
        'category',
        array( 'parent' => $cat_id, 'hide_empty' => false )
    );
    if ($children){
        return true;
    }
    return false
}

Call this from template

if(has_Children($tid)) {
    // it has children
}