Search code examples
phpajaxwordpresswoocommercetaxonomy

Get woocommerce breadcrum with taxonomy id after refreshing content with ajax


Is there a way to pass in Taxonomy ID to Woocommerce breadcrumb after updating the page with ajax. After I update page with ajax including the woocommerce_breadcrumb() function in it the breadcrumb just shows "Home" but should show the right taxonomy.

I've tried to pass in taxonomy information to my custom breadcrumb function like this.

function get_breadcrumb_with_id($taxonomy_id){
    // Get the taxonomy object
$taxonomy = get_term_by( 'id', $taxonomy_id, 'product_cat' );

// Set up the breadcrumb arguments
$args = array(
    'delimiter'   => ' > ',
    'wrap_before' => '<nav class="woocommerce-breadcrumb" itemprop="breadcrumb">',
    'wrap_after'  => '</nav>',
    'before'      => '',
    'after'       => '',
    'home'        => _x( 'Home', 'breadcrumb', 'woocommerce' ),
    'taxonomy'    => $taxonomy->taxonomy,
    'term'        => $taxonomy->slug,
);

// Display the breadcrumb
return woocommerce_breadcrumb( $args );
}

Solution

  • I made a custom Woocommerce breadcrumb function as a workaround for this issue. This works only on 2 levels. So it will look like this Home > parent cat(if there is one) > current cat.

      function custom_woocommerce_breadcrumb($term)
        {
                // Get the shop page id and URL
            $shop_page_id = get_option('woocommerce_shop_page_id');
            $shop_page_url = get_permalink($shop_page_id);
        
            $html = '<nav class="woocommerce-breadcrumb">
            <a href="'.$shop_page_url.'">'.__('Home','myshop').'</a>
            <span class="breadcrumb--delimiter"> &gt; </span>';
        
            if ($term->parent > 0) :
                $parentTerm = get_term($term->parent, 'product_cat');
                $html .= '<a href="' . get_term_link($term->parent, 'product_cat') . '">' . $parentTerm->name . '</a>
              <span class="breadcrumb--delimiter"> &gt; </span>';
            endif;
        
            $html .= $term->name . '
            </nav>';
        
            echo $html;
        }
    

    Call the function and pass in the term

    $object = get_queried_object();
    $objectId = $object->term_id;
    $term = get_term($objectId, 'product_cat');
    custom_woocommerce_breadcrumb($term);