Guest User

Dynamic Breadcrumbs woocommerce

a guest
Feb 21st, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. add_filter('woocommerce_get_breadcrumb', 'custom_woocommerce_breadcrumbs', 10, 2);
  2. function custom_woocommerce_breadcrumbs($crumbs, $breadcrumb) {
  3. $default_category_id = (int) get_option('default_product_cat'); // Get the default category ID
  4.  
  5. if (is_singular('product')) {
  6. $referer = wp_get_referer();
  7. if (!empty($referer)) {
  8. // Parse the referer URL to get the path
  9. $parsed_url = parse_url($referer);
  10. $path_segments = explode('/', trim($parsed_url['path'], '/'));
  11. $custom_crumbs = [$crumbs[0]]; // Home link
  12.  
  13. // Build custom breadcrumb from referer
  14. if (!empty($path_segments)) {
  15. foreach ($path_segments as $segment) {
  16. $term = get_term_by('slug', $segment, 'product_cat');
  17. if ($term && $term->term_id != $default_category_id) { // Exclude the default category
  18. $custom_crumbs[] = [$term->name, get_term_link($term)];
  19. }
  20. }
  21. }
  22.  
  23. // Add the current product to the custom breadcrumb
  24. $custom_crumbs[] = end($crumbs);
  25. return $custom_crumbs;
  26. }
  27. }
  28.  
  29. // Filter out the default category from all breadcrumbs if not a single product page or no referer
  30. $filtered_crumbs = [];
  31. foreach ($crumbs as $crumb) {
  32. if (isset($crumb[0]) && !term_is_ancestor_of($default_category_id, get_term_by('name', $crumb[0], 'product_cat', ARRAY_A)['term_id'], 'product_cat')) {
  33. $filtered_crumbs[] = $crumb;
  34. }
  35. }
  36.  
  37. return $filtered_crumbs;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment