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.
function set_correct_primary_category_for_woocommerce_breadcrumbs($term, $terms)
{
$taxonomy = 'product_cat';
$primary_cat_id = get_post_meta(get_the_ID(), '_yoast_wpseo_primary_' . $taxonomy, true);
$termList = [];
$terms = get_the_terms(get_the_ID(), 'product_cat');
if (!empty($terms)) {
foreach ($terms as $term) {
$termList[] = $term->term_id;
}
}
if ($primary_cat_id) {
return get_term($primary_cat_id);
}
return get_term(end($termList));
}
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.
Do you have any questions? Please feel free to leave a comment below, and I will do my best to respond as quickly as possible.
If you’re interested in more tutorials or engaging content, be sure to check out my YouTube channel