The snippet
If you want some more control over the primary category ancestry of a product’s breadcrumbs you can use the following snippet. Please note, this snippet does require you to work with Yoast SEO.
<?php
function set_correct_primary_category_for_woocommerce_breadcrumbs($term, $terms)
{
$primary_cat_id = get_post_meta(get_the_ID(), "_yoast_wpseo_primary_product_cat", true);
$terms = get_the_terms(get_the_ID(), "product_cat");
$term_ids = array_map(function($term) {
return $term->term_id;
}, $terms);
return $primary_cat_id ? get_term($primary_cat_id) : get_term(end($term_ids));
}
add_filter("woocommerce_breadcrumb_main_term", "set_correct_primary_category_for_woocommerce_breadcrumbs", 10, 2);
This piece of code figures our which categor you’ve selected as “primary”. Based on your choice it will build the ancestry (breadcrumb) accordingly. If you forget to select a primary category the snippet will fall back on the standard child.