Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a category has a parent category?

Tags:

php

wordpress

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 );
like image 842
PhatToni Avatar asked Sep 28 '13 08:09

PhatToni


People also ask

How to check if a category has any subcategories?

The variable $cat is the category ID you are checking: Use this function cat_has_subcat ('paste cat id') to check the category has any subcategories or not Thanks for contributing an answer to WordPress Development Stack Exchange! Please be sure to answer the question.

How do I check if a category has no children?

The variable $cat is the category ID you are checking: $categories = get_categories ($cat); if (!empty ($categories)) { // This Category has children } else { // This category has no children }

How to get the correct taxonomy name from a function?

You can simply now just pass the term id to the function and the correct taxonomy name if the taxonomy is anything other than category, and you will get a boolen value back just as the build in conditional tags, true on success if the term have children, false if it does not.


Video Answer


1 Answers

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
}
like image 155
The Alpha Avatar answered Nov 06 '22 04:11

The Alpha