Use Yoast primary category in WooCommerce breadcrumbs
WooCommerce breadcrumbs with Yoast primary category
When working with WooCommerce, Woo can automatically build breadcrumbs based on the product's associated categories. However, if a product is in multiple categories, it will not choose a primary category by default, but just the one it finds first. However, the Yoast SEO plugin has a built-in feature that makes it possible to choose a primary category and the category that you have chosen as the most important, most people want to be shown in their breadcrumbs rather than a random category.
By default, WooCommerce just selects a random category if there are several. This can mean that the breadcrumb shows the wrong path. Example: Home / Products / Offers
As mentioned, Yoast SEO allows you to select a primary category at the product level. We can link this into WooCommerce breadcrumbs with a small filter.
add_filter( 'woocommerce_breadcrumb_main_term', 'lc_breadcrumbs_primary_category' );
/**
* Use Yoast primary category in WooCommerce breadcrumbs.
*/
function lc_breadcrumbs_primary_category( $term ) {
if ( function_exists( 'yoast_get_primary_term_id' ) ) {
$primary_id = yoast_get_primary_term_id( 'product_cat', get_the_ID() );
if ( $primary_id && ! is_wp_error( $primary_id ) ) {
$primary_term = get_term( (int) $primary_id, 'product_cat' );
if ( $primary_term && ! is_wp_error( $primary_term ) ) {
return $primary_term;
}
}
}
return $term;
}How does the feature work?
- woocommerce_breadcrumb_main_term allows us to determine which category WooCommerce should use as a starting point.
- The feature checks if Yoast SEO is installed.
- If a primary category is selected, it will be returned.
- WooCommerce takes care of building the breadcrumb path correctly - including parent categories if the primary category is a child.