Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- add_filter('woocommerce_get_breadcrumb', 'custom_woocommerce_breadcrumbs', 10, 2);
- function custom_woocommerce_breadcrumbs($crumbs, $breadcrumb) {
- $default_category_id = (int) get_option('default_product_cat'); // Get the default category ID
- if (is_singular('product')) {
- $referer = wp_get_referer();
- if (!empty($referer)) {
- // Parse the referer URL to get the path
- $parsed_url = parse_url($referer);
- $path_segments = explode('/', trim($parsed_url['path'], '/'));
- $custom_crumbs = [$crumbs[0]]; // Home link
- // Build custom breadcrumb from referer
- if (!empty($path_segments)) {
- foreach ($path_segments as $segment) {
- $term = get_term_by('slug', $segment, 'product_cat');
- if ($term && $term->term_id != $default_category_id) { // Exclude the default category
- $custom_crumbs[] = [$term->name, get_term_link($term)];
- }
- }
- }
- // Add the current product to the custom breadcrumb
- $custom_crumbs[] = end($crumbs);
- return $custom_crumbs;
- }
- }
- // Filter out the default category from all breadcrumbs if not a single product page or no referer
- $filtered_crumbs = [];
- foreach ($crumbs as $crumb) {
- 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')) {
- $filtered_crumbs[] = $crumb;
- }
- }
- return $filtered_crumbs;
- }
Advertisement
Add Comment
Please, Sign In to add comment