True Breadcrumbs in Pro and Woocommerce

Hi.

I found this code here to add a trail of breadcrumbs on my page.

add_filter('x_breadcrumbs_data', 'post_parent_trail', 9999999, 2);
function post_parent_trail ($crumbs, $args) {
	if ( is_singular('product') ) {
		global $product;
		$category = get_the_terms( $product->ID, 'product_cat' );

		if ( count( $category ) > 0 ) {

			$cat_array             = array();
			$cat_array[1]['label'] = $category[0]->name;
			$cat_array[1]['url']   = get_term_link( $category[0]->term_id );

			array_splice($crumbs, 2, 0, $cat_array);
		}
	}
	return $crumbs;  
}

Its showing for example Home > Shop > Wall Art > product name.

However, the product is under a sub-category of Wall Art, which is “Posters”. Any possibility to tweak the code to show:
Home > Shop > Wall Art > Posters > product code ?

Thank you.

Hello Fauzi,

Thanks for writing in!

Please update your code and use this:

// Categories and Subcategories in breadcrumb
// =============================================================================
add_filter('x_breadcrumbs_data', 'post_parent_trail', 9999999, 2);
function post_parent_trail ($crumbs, $args) {
  if ( is_singular('product') ) {
    global $product;
    $category = get_the_terms( $product->ID, 'product_cat' );
    
    if ( count( $category ) > 0 ) {
      $cat_array             = array();
      $count = 0;
      foreach( $category as $cat ) {

        $cat_array[$count]['label'] = $cat->name;
        $cat_array[$count]['url']   = get_term_link( $cat->term_id );
        $count++;
      }

      $cat_array = array_reverse($cat_array);

      array_splice($crumbs, 2, 0, $cat_array);
    }
  }
  return $crumbs;  
}
// =============================================================================

And then the Home > Category > SubCategory> product name will display. Just make sure that the product is assigned to both the category and subcategory. If not, only one of those two will appear.

Please let us know how it goes.

Amazing! Thank you so much. It always amaze me on how gifted you guys are! :smiley:

You’re welcome!
We’re glad we were able to help you out.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.