WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Get topmost category parent (2 posts)

  1. termserv
    Member
    Posted 5 years ago #

    I found a script here in the forums that returned the topmost post parent, but I need to get the topmost category parent (preferrably the ID)?

  2. termserv
    Member
    Posted 5 years ago #

    I made it work with the following function:

    function in_parent_category($cats, $_post = null)
    {
    	foreach ((array) $cats as $cat)
    	{
    		$descendants = get_term_children((int) $cat, "category");
    		if ($descendants && in_category($descendants, $_post))
    			return true;
    	}
    	return false;
    }

    Just feed the function with the category ID of the parent, and then it checks the current post (if in the loop) if it's in a category which is a child of the category ID you specify.

    if (in_parent_category(4))
    {
    	// do this
    }

Topic Closed

This topic has been closed to new replies.

About this Topic