Hi,
as far as I know, you cannot solve this with liquid in the way you want it, as long as products are in multiple collections at the same time.
There are a few scenarios and how you could solve them.
Products are only in one collection
Use the collections object in the product object and pick the first (and only) collection
This way, you could always show a collection breadcrumb, even if no additional information is present in the product URL.
Docs: https://shopify.dev/docs/api/liquid/objects/product#product-collections
Products are in multiple collections
- Use JavaScript to (save and) get the previous page
There are some ways to get the previous page with Javascript, especially if you saved it before. With that, you could dynamically build the breadcrumb during the page load for the customer, even if it is not in the HTML response from Shopify.
A possible starting point: https://rswpthemes.com/how-to-get-previous-page-url-in-javascript
- Use the
collections object in the product object and pick the first collection
This way, you could always show a collection breadcrumb, even if no additional information is present in the product URL.
However, it might not be the collection the customer came from.
Docs: https://shopify.dev/docs/api/liquid/objects/product#product-collections
- Use the “within” filter (https://shopify.dev/docs/api/liquid/filters/within), which means having a different URL structure
If your only concern are canonical issues and SEO implications, they can be solved with canonical URL meta tags, which most Shopify theme is already setting anyway.
Or you could use some JavaScript after the page has loaded to change the URL after the page has loaded, which would be just decorative for users, but not real URLs.
- Use JavaScript or Liquid to add a query string to the product URL, containing the collection handle
This again changes the URL, but would allow you to build breadcrumbs with it.
Again, you could clean up the URL for users by removing the query string later.
Good luck!
Joda