Support » Developing with WordPress » Adding Parent Category to Breadcrumbs

  • Hi there,

    I was wondering if anyone would be so kind as to help me figure out how to add the “parent category” to my breadcrumbs hierarchy. Currently I am seeing Home > Category > Post but I would like to see Home > Parent Category > Category > Post. This is the code I’m currently using in my functions.php to display the “category”

    add_filter('x_breadcrumbs_data', 'post_parent_trail', 9999999, 2);
    
    	function post_parent_trail ($crumbs, $args) {
    		if ( is_singular('post') ) {
    
    			$category = get_the_category( get_the_ID() );
    
    				if ( count( $category ) > 0 ) {
    
    					$cat_array = array();
    					$cat_array[1]['label'] = $category[0]->name;
    					$cat_array[1]['url'] = get_category_link( $category[0]->term_id );
    
    					array_splice($crumbs, 2, 0, $cat_array);
    				}
    		}
    	return $crumbs;  
    }

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    The category object includes a “parent” property which contains the ID of any parent category. If the value is zero, the current category is a top level term. Thus, if the value is non-zero, get that category by ID and generate the appropriate data for the $crumbs array. If this is done thoughtfully, the process could be done recursively so a single function call can handle any number of hierarchical levels.

    The logical way to work up to the top level term from any descendant would result in the category crumb trail being backwards. Use array_reverse() to flip it around into the proper order prior to splicing into $crumbs.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.