WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How do I tell if a category is a parent? (5 posts)

  1. Rebecca Schaefer
    Member
    Posted 5 years ago #

    Is there a function hidden away somewhere, like is_parent() or has_parent()? I need to find a way to distinguish between parents and children in an if statement, so I figure the best way is to select only categories that have no parent. Any ideas?

  2. Rebecca Schaefer
    Member
    Posted 5 years ago #

    OK, got it resolved.

  3. funbsd
    Member
    Posted 5 years ago #

    Can you tell me how?

  4. darthead
    Member
    Posted 5 years ago #

    It would be great if you'd share your solution with us. Thanks!

  5. darthead
    Member
    Posted 5 years ago #

    This is how I did it:

    //Specify the parent category
    $parent_cat = "Category";
    //get all categories
    $categories = get_categories();
    //loop through categories
    foreach ($categories as $cat) :
    	//retrieve category path string (i.e., 'Category/Sub-Category/')
    	$cat_str = get_category_parents( $cat->cat_ID );
    	//if current $cat has a parent (is not top-level) and $cat_str contains the $parent_cat string
    	if($cat->parent && stristr($cat_str, $parent_cat)) :

    get_category_parents() takes the current category id and returns a string with the category path, including itself, such as

    Category/

    Category/Sub-category/

    Category/Sub-category/Sub-category/

    the 'if' statement checks to make sure the current $cat is not top-level and that the parent string contains the parent category specified in $parent_cat, which excludes posts from other top-level categories.

Topic Closed

This topic has been closed to new replies.

About this Topic