Roots Discourse

Woocommerce breadcrumbs for multiple categories with browsing history and a primary category


I needed smarter breadcrumbs for the products so they follow the browsing path or else stick with a default category (which now it decides randomly in practice).

As there are no posted solutions for this problem that I could find, only outdated ones that don’t work, I share my code for anyone to use. Please share if you find faster or better solutions.

In single-product.blade.php or filters with a conditional:

    function breadcumbs_referred_or_primary ($main, $terms)
      // Our primary term is 520 (hardcoded)
      // we get the first primary term
      // we retrieve the breadcrumbs from referrer page

      $referer = wp_get_referer();
      $referredTerm = -1;
      $referredTermIndex = -1;
      $primaryTermId = 520; // hardcoded
      $primaryTermIndex = -1;

      foreach($terms as $key => $term) {
				if ($referredTerm != -1) break; // we found it in a previous iteration!

        $ancestors = get_ancestors( $term->term_id, 'product_cat');
        array_unshift($ancestors, $term->term_id);
        if ($primaryTermIndex == -1 && in_array($primaryTermId, $ancestors)) $primaryTermIndex = $key;

        foreach ($ancestors as $ancestor) {
          if($referredTerm != -1) break 2; // we found it in a previous iteration!
          $ancestor = get_term( $ancestor, 'product_cat' );
          $referer_slug = (strpos($referer, '/'.$ancestor->slug.'/'));

          if (!$referer_slug==false) { // it's found in the current level
            $referredTerm = $term->term_id;
            $referredTermIndex = $key;

      // we return either the browsed terms or the primary term
      if ($referredTermIndex != -1) {
        return $terms[$referredTermIndex];
      } else {
        return $terms[$primaryTermIndex];

    add_filter('woocommerce_breadcrumb_main_term', 'breadcumbs_referred_or_primary', 10, 2);

This topic was automatically closed after 42 days. New replies are no longer allowed.