De Belser Arne Profielfoto

Arne De Belser

Set correct primary category for woocommerce breadcrumbs with Yoast SEO

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.

				
					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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x