Accessing the WooCommerce BreadCrumbs from Plugin Code

After a couple of hours of searching, plus trial and error. I was able to figure out how to get the category breadcrumbs into my plugin and work with the data.

Unfortunately, this is very poorly documented, and evidently not frequently attempted, because I could not find a single post anywhere that described this.

Here's my situation: a WooCommerce site with a large number of categories, which go sometimes go 4 levels deep. And at that level there are many with the same category names - eg: "proof". So the display of category name in itself was not enough, I needed the whole path, so the person would know what page he's looking at.

Now, adding a breadcrumb is easy enough. But I wanted to leave that alone and have a different layout for the full category name. That seemed to be not so easy.

Eventually, after digging into the WooCommerce source code, I found the solution.

Here's the final code for my shortcode:

add_shortcode('categoryPath', function ($atts) {
  return "Category: ". implode(" / ", array_map(function ($elem) {
    return $elem[0];
  }, (new \WC_Breadcrumb())->generate()));

});

The WC_Breadcrumb class is the key. (I used a leading \ because I had a namespace defined in my file). Its generate() method creates an array of [category name, category url] 2 element arrays. That does not include the home page.

I just extracted the category name with the array_map and then made it into a string separated by /s.

For the sake of completeness, here the code to get access to the breadcrumbs before the page is rendered:

add_action('parse_query', function(){
  $breadCrumbs=(new \WC_Breadcrumb())->generate();
  ....
});

The parse_query hook is the earliest phase where this will work (found it out by trial and error). I used this list for reference on the sequence of "actions" in WordPress https://codex.wordpress.org/Plugin_API/Action_Reference

Note: I prefer to use anonymous functions in the callback parameters, instead of the string reference that is usually used in examples. Unless you have a very old PHP version, then you can use these. It eliminates the need for creating an extra named function which is then not used anywhere else (namespace pollution). Plus it keeps the code pieces that belong together, together.

No Comments Yet