WordPress.org

Ready to get started?Download WordPress

Forums

is child of specific category (2 posts)

  1. chugs
    Member
    Posted 5 years ago #

    What I am trying to do -

    <?php if (is_category('categoryname') || in_category('1') || is_category('child_of=1')) ?>
    
    ~ do this ~
    
    else
    
    ~ do something else ~

    what I am stuck at is finding out whether the current category is the child/grandchild of a particular category.

    Any pointers?

  2. GeertDD
    Member
    Posted 4 years ago #

    I've been looking for the same functionality. However, since I didn't found exactly what I was looking for, here is a custom built function:

    /**
     * @param  integer  parent category ID
     * @param  integer  child category ID
     * @return  boolean
     */
    function is_child_of_category($category_id, $child_category_id = NULL)
    {
    	// Load all children of the category
    	$children = get_categories('child_of='.$category_id.'&hide_empty=0');
    
    	// Initialize an array for all child IDs
    	$children_ids = array();
    
    	// Fill the array just with category IDs
    	foreach ($children as $child)
    	{
    		$children_ids[] = $child->cat_ID;
    	}
    
    	// Check whether the given child ID, or the current category, exists within the category
    	return ($child_category_id !== NULL)
    		? in_array($child_category_id, $children_ids)
    		: is_category($children_ids);
    }

    Hmm, this may be even better: cat_is_ancestor_of().

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.