• I’m trying to use get_category_parents in a category archive page (category.php)

    I pick up the title, ID and full category object for the category whose archive we’re looking at:

    $catTitle = single_cat_title('', false);
    $catID = get_cat_ID($catTitle);
    $cat = get_the_category($catID);

    The ‘main’ category title is displayed up at the top of the page, so, when I get to display its ‘parents’ (ascendants, really), I wish to ‘skip’ the category itself.

    So I looked around and noticed that the source for get_category_parents include a $visited array (See line 53 over here) – figured I could use it. So:

    $preventDuplicate = array();
    $preventDuplicate[] = $catID;

    Followed by:

    <ul class="breadcrumb for-category">
    	<li><?php echo get_category_parents($catID, true, '</li><li>', false, $preventDuplicate); ?></li>
    </ul>

    I have a category called ‘sub’ that is set as a child of a category named ‘aciform’. When this code runs and I’m looking at the archive for ‘sub’, the get_category_parents still produces the ‘last’ item for the leaf (‘sub’)

    The more I stare at the source for get_category_parents the more I think $visited is not checked for the ‘current’ category, but only as we are ready to pop up the ladder to the parent (if any) of the current node. Which could be a suggestion for future version…
    …but in the meanwhile, is there something I’m doing worng, or something else I should do to make get_category_parents skip the leaf?

    Thank you in advance,
    FR

Viewing 1 replies (of 1 total)
  • Thread Starter FrancescoRizzi

    (@francescorizzi)

    I realized in my original post I was erroneously using get_the_category to retrieve the category – should have been get_category instead.

    Anyways, my current solution below for anyone else who may need this – still interested to see if there was a built-in solution to my situation so I’m leaving this open for now

    if ( ! function_exists( 'FRD_CategoryAscendants' ) ):
    function FRD_CategoryAscendants($leafID, $skipLeaf = false) {
    	$visited = array();
    	$categories = array();
    
    	$current = get_category($leafID);
    	if(!empty($current)) {
    
    		$visited[] = $current->ID;
    		if(!$skipLeaf) {
    			$categories[] = $current;
    		}
    
    		while($current->parent) {
    			$parent = get_category($current->parent);
    			if(!in_array($parent->term_id, $visited)) {
    				$categories[] = $parent;
    				$visited[] = $parent->term_id;
    			}
    			$current=$parent;
    		}
    		$categories = array_reverse($categories);
    	}
    	return $categories;
    }
    endif;
Viewing 1 replies (of 1 total)
  • The topic ‘Skipping the leaf?’ is closed to new replies.