WordPress.org

Ready to get started?Download WordPress

Forums

How can I tell if a sub category is child of a sub category? (2 posts)

  1. Daiv Mowbray
    Member
    Posted 5 years ago #

    I'm trying to get a plugin to identify a child of a child.
    parent category
    - child category
    - - child of child category (I need to identify this)
    - - - child of child of child category (I need to identify this as well)

  2. yoshi
    Member
    Posted 5 years ago #

    If you are using permalink, use get_category_link and check the url (e.g. numbers of '/'s) is one way.

    You can also keep looking up $category->parent if the category has 2 or more ancestors.

    parent category (depth:0)
    - child category (depth:1)
    - - child of child category (depth:2, ID:10)
    - - - child of child of child category (depth:3, ID:11)

    <?php
    function cat_deeper_than($depth = 1, $cat_id = 0) {
      $cat = get_category($cat_id);
      if (!$cat->parent) return false;
      if ($depth <= 0) return ture;
      return cat_deeper_than($depth - 1, $cat->parent);
    }
    
    echo cat_deeper_than(1, 11) ? 'child of sub category' : 'this is not';
    echo cat_deeper_than(1, 12) ? 'child of sub category' : 'this is not';
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic