Support » Fixing WordPress » How do I tell if a category is a parent?

  • Resolved Rebecca O'Brien


    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?

Viewing 4 replies - 1 through 4 (of 4 total)
  • OK, got it resolved.

    Can you tell me how?

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

    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




    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.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How do I tell if a category is a parent?’ is closed to new replies.