Home » 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.

<?php

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

Abonneer
Laat het weten als er
guest
0 Comments
Inline feedbacks
Bekijk alle reacties
0
Zou graag je mening willen weten, laat een reactie achter.x