phpwordpresswoocommercebreadcrumbs

Woocommerce breadcrumbs multiple categories


I have e commerce website in wordpress. There are lot of product in it & many product comes under multiple categories like 600 mah Power bank is comes under automobile, IT, media etc. My problem is when i go to the detail of a product there it by default pick up only one category no matter if go through IT category at the end it shows me automobile like this Home / Shop / industry / Automobile / 600 mah Power Bank. But i went to this product via IT so it should show me like this Home / Shop / industry / IT / 600 mah Power Bank. How can iget path where i come from previous page?


Solution

  • if you are using Woocommerce you can use the following directly, if not it will need adapting but you get the idea:

    if (get_post_type() == 'product' && is_single() && ! is_attachment()) {
        echo $prepend;
    
        if ($terms = get_the_terms($post->ID, 'product_cat')) {
            $referer = wp_get_referer();
            foreach ($terms as $term) {
                $referer_slug = (strpos($referer, $term->slug));
    
                if ($referer_slug == true) {
                    $category_name = $term->name;
                    $ancestors = get_ancestors($term->term_id, 'product_cat');
                    $ancestors = array_reverse($ancestors);
    
                    foreach ($ancestors as $ancestor) {
                        $ancestor = get_term($ancestor, 'product_cat');
    
                        if (! is_wp_error($ancestor) && $ancestor) {
                            echo $before . '<a href="' . get_term_link($ancestor->slug, 'product_cat') . '">' . $ancestor->name . '</a>' . $after . $delimiter;
                        }
                    }
                    echo $before . '<a href="' . get_term_link($term->slug, 'product_cat') . '">' . $category_name . '</a>' . $after . $delimiter;
                }
            }
        }
    
        echo $before . get_the_title() . $after;
    }
    

    The main bulk of the work here is done by wp_get_referer which gets the referring URL of the product your visitor has navigated to. The rest of the code checks if a valid category is contained within the URL and uses it in the breadcrumb.

    See Jonathon Js post here for more information http://www.cryoutcreations.eu/forums/t/wrong-breadcrumbs-displayed