• Hi! I have been struggling with this matter asked also in this topic

    As it didn’t work for me and the topic is closed although it’s the first page result in google, I share my code which uses the filtering approach.

    You can use this code in the single-product template or in functions.php with a conditional for single product page. I believe it can be improved but for my use case it works. Feel free to post better solutions!

    It will get the breadcrumbs related to your browsing history, or if it can’t, it will show the breadcrumbs related to a primary category (in my case 520).

    
    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 modified 4 years, 2 months ago by sergiarias.
Viewing 1 replies (of 1 total)
  • Thanks, it seems to be working!

    I am trying to figure out the 520 part though

    * Accidentally sent this message, can’t delete it

    • This reply was modified 4 years, 2 months ago by metdark. Reason: Why can't I delete this message?
Viewing 1 replies (of 1 total)
  • The topic ‘Breadcrumbs for products in multiple categories (2020 update)’ is closed to new replies.