Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.9 kB
3
Indexable
Never
function flatten_hierarchy($hierarchy) {
    $result = array();

    foreach ($hierarchy as $term) {
        $result[] = $term;
        if (!empty($term->children)) {
            $result = array_merge($result, flatten_hierarchy($term->children));
        }
    }

    return $result;
}

function remove_duplicate_terms($links) {
    $processed_terms = array();
    $cleaned_links = array();

    foreach ($links as $link) {
        if (isset($link['term_id']) && in_array($link['term_id'], $processed_terms)) {
            continue;
        }

        if (isset($link['term_id'])) {
            $processed_terms[] = $link['term_id'];
        }

        $cleaned_links[] = $link;
    }

    return $cleaned_links;
}

function custom_wpseo_breadcrumbs($links) {
    global $post;

    if (is_singular('offer')) {
        $terms = wp_get_post_terms($post->ID, 'localization', array('orderby' => 'parent', 'order' => 'DESC'));

        if ($terms && !is_wp_error($terms)) {
            $hierarchy = build_taxonomy_hierarchy($terms);
            $sorted_terms = flatten_hierarchy($hierarchy);

            $term_links = array();
            foreach ($sorted_terms as $term) {
                $term_links[] = array(
                    'url' => get_term_link($term),
                    'text' => $term->name,
                    'term_id' => $term->term_id,
                    'taxonomy' => 'localization'
                );
            }

            array_pop($links);

            $links = array_merge($links, $term_links);

            $links[] = array(
                'url' => get_permalink($post->ID),
                'text' => $post->post_title
            );

            $links = remove_duplicate_terms($links);
        }
    }

    return $links;
}
add_filter('wpseo_breadcrumb_links', 'custom_wpseo_breadcrumbs');