<?php
/**
 * Breadcrumbs Appia Antica
 *
 * Frontend renderer for the Etch component marker:
 * data-breadcrumbs-appia-antica-root
 */

if (!defined('ABSPATH')) {
    exit;
}

if (!function_exists('baa_bool')) {
    function baa_bool($value, bool $default = true): bool {
        if ($value === null || $value === '') {
            return $default;
        }

        $value = strtolower(trim((string) $value));

        if (in_array($value, ['true', '1', 'yes', 'on'], true)) {
            return true;
        }

        if (in_array($value, ['false', '0', 'no', 'off'], true)) {
            return false;
        }

        return $default;
    }
}

if (!function_exists('baa_trail_source')) {
    function baa_trail_source($value): string {
        $value = strtolower(trim((string) $value));

        return in_array($value, ['permalink', 'permalink path'], true)
            ? 'permalink'
            : 'context';
    }
}

if (!function_exists('baa_truncate')) {
    function baa_truncate(string $text, int $max, string $ellipsis = '...'): array {
        if ($max <= 0) {
            return [$text, false];
        }

        $has_mb = function_exists('mb_strlen') && function_exists('mb_substr');
        $length = $has_mb ? mb_strlen($text, 'UTF-8') : strlen($text);

        if ($length <= $max) {
            return [$text, false];
        }

        $ellipsis_length = $has_mb ? mb_strlen($ellipsis, 'UTF-8') : strlen($ellipsis);
        $slice = max(0, $max - $ellipsis_length);
        $cut = $has_mb
            ? mb_substr($text, 0, $slice, 'UTF-8')
            : substr($text, 0, $slice);

        return [rtrim($cut) . $ellipsis, true];
    }
}

if (!function_exists('baa_inline_svg')) {
    function baa_inline_svg(string $url, string $class, string $style = ''): string {
        $url = esc_url_raw(trim($url));

        if (!$url) {
            return '';
        }

        $path = strtolower((string) wp_parse_url($url, PHP_URL_PATH));

        if (substr($path, -4) !== '.svg') {
            return '';
        }

        $response = wp_safe_remote_get($url, [
            'timeout' => 5,
            'redirection' => 2,
        ]);

        if (is_wp_error($response)) {
            return '';
        }

        $code = (int) wp_remote_retrieve_response_code($response);

        if ($code < 200 || $code >= 300) {
            return '';
        }

        $svg = wp_remote_retrieve_body($response);

        if (!$svg || stripos($svg, '<svg') === false) {
            return '';
        }

        $svg = preg_replace('/<\?xml.*?\?>/is', '', $svg);
        $svg = preg_replace('/<!doctype.*?>/is', '', $svg);
        $svg = preg_replace('/<script\b[^>]*>.*?<\/script>/is', '', $svg);
        $svg = preg_replace('/<foreignObject\b[^>]*>.*?<\/foreignObject>/is', '', $svg);
        $svg = preg_replace('/\son\w+="[^"]*"/i', '', $svg);
        $svg = preg_replace("/\son\w+='[^']*'/i", '', $svg);
        $svg = preg_replace('/\s(?:href|xlink:href)=["\']\s*javascript:[^"\']*["\']/i', '', $svg);

        $classes = preg_split('/\s+/', trim($class));
        $classes = array_filter(array_map('sanitize_html_class', (array) $classes));
        $class = implode(' ', $classes);
        $style_attr = $style !== '' ? ' style="' . esc_attr($style) . '"' : '';
        $svg = preg_replace(
            '/<svg\b([^>]*)>/i',
            '<svg$1 class="' . esc_attr($class) . '"' . $style_attr . ' aria-hidden="true" focusable="false">',
            $svg,
            1
        );

        return trim((string) $svg);
    }
}

if (!function_exists('baa_item')) {
    function baa_item(
        string $label,
        $url = null,
        bool $current = false,
        bool $is_current_post = false,
        bool $is_home = false,
        bool $resolved = true,
        string $source = ''
    ): array {
        return [
            'label' => $label,
            'url' => $url,
            'current' => $current,
            'is_current_post' => $is_current_post,
            'is_home' => $is_home,
            'resolved' => $resolved,
            'source' => $source,
        ];
    }
}

if (!function_exists('baa_normalize_url')) {
    function baa_normalize_url(string $url): string {
        $parts = wp_parse_url($url);

        if (!is_array($parts) || empty($parts['host'])) {
            return untrailingslashit($url);
        }

        $scheme = isset($parts['scheme']) ? strtolower((string) $parts['scheme']) : 'https';
        $host = strtolower((string) $parts['host']);
        $port = isset($parts['port']) ? ':' . (int) $parts['port'] : '';
        $path = isset($parts['path']) ? '/' . ltrim((string) $parts['path'], '/') : '';

        return untrailingslashit($scheme . '://' . $host . $port . $path);
    }
}

if (!function_exists('baa_dedupe_items')) {
    function baa_dedupe_items(array $items): array {
        $result = [];
        $seen = [];

        foreach ($items as $item) {
            if (empty($item['label'])) {
                continue;
            }

            $key = !empty($item['url'])
                ? 'url:' . baa_normalize_url((string) $item['url'])
                : 'label:' . strtolower(wp_strip_all_tags((string) $item['label']));

            if (isset($seen[$key])) {
                if (!empty($item['current']) && isset($result[$seen[$key]])) {
                    $result[$seen[$key]]['url'] = null;
                    $result[$seen[$key]]['current'] = true;
                    $result[$seen[$key]]['is_current_post'] = !empty($item['is_current_post']);
                }

                continue;
            }

            $seen[$key] = count($result);
            $result[] = $item;
        }

        return array_values($result);
    }
}

if (!function_exists('baa_add_post_type_archive')) {
    function baa_add_post_type_archive(string $post_type, array &$items): void {
        $post_type = sanitize_key($post_type);

        if (!$post_type || $post_type === 'page') {
            return;
        }

        if ($post_type === 'post') {
            $page_for_posts = (int) get_option('page_for_posts');

            if ($page_for_posts) {
                $items[] = baa_item(
                    (string) get_the_title($page_for_posts),
                    get_permalink($page_for_posts),
                    false,
                    false,
                    false,
                    true,
                    'posts-page'
                );
            }

            return;
        }

        $object = get_post_type_object($post_type);
        $url = get_post_type_archive_link($post_type);

        if (!$object || !$url) {
            return;
        }

        $label = apply_filters('baa_post_type_label', $object->labels->name, $post_type);
        $items[] = baa_item((string) $label, $url, false, false, false, true, 'post-type-archive');
    }
}

if (!function_exists('baa_get_taxonomy_archive_post_type')) {
    function baa_get_taxonomy_archive_post_type(string $taxonomy): string {
        $taxonomy = sanitize_key($taxonomy);

        if (!$taxonomy || !taxonomy_exists($taxonomy)) {
            return '';
        }

        $object = get_taxonomy($taxonomy);

        if (!$object || empty($object->object_type)) {
            return '';
        }

        $post_types = array_values(array_filter((array) $object->object_type));

        foreach ($post_types as $post_type) {
            $post_type = sanitize_key((string) $post_type);

            if ($post_type && !in_array($post_type, ['post', 'page'], true) && get_post_type_archive_link($post_type)) {
                return $post_type;
            }
        }

        return $post_types ? sanitize_key((string) reset($post_types)) : '';
    }
}

if (!function_exists('baa_add_taxonomy_trail')) {
    function baa_add_taxonomy_trail(int $post_id, string $taxonomy, array &$items): void {
        $taxonomy = sanitize_key($taxonomy);

        if (!$taxonomy || !taxonomy_exists($taxonomy)) {
            return;
        }

        $terms = get_the_terms($post_id, $taxonomy);

        if (empty($terms) || is_wp_error($terms)) {
            return;
        }

        $term = reset($terms);

        if (!$term || is_wp_error($term)) {
            return;
        }

        if (!empty($term->parent)) {
            $parents = array_reverse(get_ancestors($term->term_id, $taxonomy, 'taxonomy'));

            foreach ($parents as $parent_id) {
                $parent = get_term($parent_id, $taxonomy);

                if ($parent && !is_wp_error($parent)) {
                    $items[] = baa_item($parent->name, get_term_link($parent), false, false, false, true, 'term');
                }
            }
        }

        $items[] = baa_item($term->name, get_term_link($term), false, false, false, true, 'term');
    }
}

if (!function_exists('baa_build_context_items')) {
    function baa_build_context_items(array $args): array {
        $items = [];

        if (is_singular()) {
            $post = get_queried_object();

            if (!$post || empty($post->ID)) {
                return [];
            }

            $post_type = (string) get_post_type($post);

            if (!empty($args['show_post_type'])) {
                baa_add_post_type_archive($post_type, $items);
            }

            if (
                !empty($args['show_parents']) &&
                is_post_type_hierarchical($post_type) &&
                !empty($post->post_parent)
            ) {
                foreach (array_reverse(get_post_ancestors($post->ID)) as $ancestor_id) {
                    $items[] = baa_item(
                        (string) get_the_title($ancestor_id),
                        get_permalink($ancestor_id),
                        false,
                        false,
                        false,
                        true,
                        'post-parent'
                    );
                }
            }

            if (!empty($args['show_taxonomy'])) {
                baa_add_taxonomy_trail((int) $post->ID, (string) $args['taxonomy'], $items);
            }

            if (!empty($args['show_current'])) {
                $items[] = baa_item(
                    (string) get_the_title($post->ID),
                    null,
                    true,
                    true,
                    false,
                    true,
                    'current-post'
                );
            }

            return $items;
        }

        if (is_post_type_archive()) {
            if (!empty($args['show_current'])) {
                $post_type = get_query_var('post_type');
                $post_type = is_array($post_type) ? reset($post_type) : $post_type;
                $post_type = sanitize_key((string) $post_type);
                $label = post_type_archive_title('', false);
                $label = apply_filters('baa_post_type_label', $label, $post_type);
                $items[] = baa_item((string) $label, null, true, false, false, true, 'current-archive');
            }

            return $items;
        }

        if (is_tax() || is_category() || is_tag()) {
            $term = get_queried_object();

            if (!$term || is_wp_error($term)) {
                return [];
            }

            if (!empty($args['show_post_type'])) {
                $post_type = sanitize_key((string) $args['taxonomy_archive_post_type']);

                if (!$post_type) {
                    $post_type = baa_get_taxonomy_archive_post_type((string) $term->taxonomy);
                }

                if ($post_type) {
                    baa_add_post_type_archive($post_type, $items);
                }
            }

            if (!empty($args['show_parents']) && !empty($term->parent)) {
                $parents = array_reverse(get_ancestors($term->term_id, $term->taxonomy, 'taxonomy'));

                foreach ($parents as $parent_id) {
                    $parent = get_term($parent_id, $term->taxonomy);

                    if ($parent && !is_wp_error($parent)) {
                        $items[] = baa_item($parent->name, get_term_link($parent), false, false, false, true, 'term-parent');
                    }
                }
            }

            if (!empty($args['show_current'])) {
                $items[] = baa_item($term->name, null, true, false, false, true, 'current-term');
            }

            return $items;
        }

        if (!empty($args['show_current'])) {
            $label = baa_current_query_label();

            if ($label !== '') {
                $items[] = baa_item($label, null, true, false, false, true, 'current-query');
            }
        }

        return $items;
    }
}

if (!function_exists('baa_current_query_label')) {
    function baa_current_query_label(): string {
        if (is_singular()) {
            return wp_strip_all_tags((string) get_the_title(get_queried_object_id()));
        }

        if (is_post_type_archive()) {
            return wp_strip_all_tags((string) post_type_archive_title('', false));
        }

        if (is_tax() || is_category() || is_tag()) {
            return wp_strip_all_tags((string) single_term_title('', false));
        }

        if (is_home()) {
            $page_for_posts = (int) get_option('page_for_posts');
            return $page_for_posts
                ? wp_strip_all_tags((string) get_the_title($page_for_posts))
                : __('Posts', 'baa');
        }

        if (is_search()) {
            return sprintf(__('Search results for "%s"', 'baa'), get_search_query());
        }

        if (is_404()) {
            return __('Page not found', 'baa');
        }

        if (is_author()) {
            $author = get_queried_object();
            return !empty($author->display_name) ? (string) $author->display_name : '';
        }

        if (is_archive()) {
            return wp_strip_all_tags((string) get_the_archive_title());
        }

        return '';
    }
}

if (!function_exists('baa_request_segments')) {
    function baa_request_segments(): array {
        global $wp;

        $path = isset($wp->request) ? trim((string) $wp->request, '/') : '';

        if ($path === '') {
            $request_uri = wp_unslash($_SERVER['REQUEST_URI'] ?? '');
            $path = trim((string) wp_parse_url($request_uri, PHP_URL_PATH), '/');
            $home_path = trim((string) wp_parse_url(home_url('/'), PHP_URL_PATH), '/');

            if ($home_path !== '' && strpos($path, $home_path . '/') === 0) {
                $path = substr($path, strlen($home_path) + 1);
            }
        }

        $segments = array_values(array_filter(explode('/', $path), 'strlen'));
        $count = count($segments);

        if ($count >= 2 && $segments[$count - 2] === 'page' && ctype_digit($segments[$count - 1])) {
            $segments = array_slice($segments, 0, -2);
        }

        return $segments;
    }
}

if (!function_exists('baa_match_singular_canonical_segments')) {
    function baa_match_singular_canonical_segments(array $segments): array {
        if (!is_singular() || !$segments) {
            return $segments;
        }

        $permalink = get_permalink(get_queried_object_id());

        if (!$permalink) {
            return $segments;
        }

        $canonical_path = trim((string) wp_parse_url($permalink, PHP_URL_PATH), '/');
        $home_path = trim((string) wp_parse_url(home_url('/'), PHP_URL_PATH), '/');

        if ($home_path !== '' && strpos($canonical_path, $home_path . '/') === 0) {
            $canonical_path = substr($canonical_path, strlen($home_path) + 1);
        }

        $canonical = array_values(array_filter(explode('/', $canonical_path), 'strlen'));

        if (!$canonical || count($canonical) >= count($segments)) {
            return $segments;
        }

        if (array_slice($segments, 0, count($canonical)) === $canonical) {
            return $canonical;
        }

        return $segments;
    }
}

if (!function_exists('baa_archive_map')) {
    function baa_archive_map(): array {
        static $map = null;

        if (is_array($map)) {
            return $map;
        }

        $map = [];
        $post_types = get_post_types(['has_archive' => true], 'objects');

        foreach ($post_types as $post_type) {
            $url = get_post_type_archive_link($post_type->name);

            if ($url) {
                $map[baa_normalize_url($url)] = [
                    'label' => (string) $post_type->labels->name,
                    'post_type' => (string) $post_type->name,
                ];
            }
        }

        $page_for_posts = (int) get_option('page_for_posts');

        if ($page_for_posts) {
            $url = get_permalink($page_for_posts);

            if ($url) {
                $map[baa_normalize_url($url)] = [
                    'label' => (string) get_the_title($page_for_posts),
                    'post_type' => 'post',
                ];
            }
        }

        return $map;
    }
}

if (!function_exists('baa_resolve_permalink_segment')) {
    function baa_resolve_permalink_segment(string $url, string $segment, array $context): array {
        static $base_cache = [];

        $cache_key = baa_normalize_url($url);

        if (isset($base_cache[$cache_key])) {
            $resolved = $base_cache[$cache_key];
        } else {
            $resolved = [
                'label' => '',
                'url' => null,
                'resolved' => false,
                'source' => 'fallback',
                'object_id' => 0,
            ];

            $post_id = url_to_postid($url);

            if ($post_id) {
                $permalink = get_permalink($post_id);

                if ($permalink && baa_normalize_url($permalink) === $cache_key) {
                    $resolved = [
                        'label' => wp_strip_all_tags((string) get_the_title($post_id)),
                        'url' => $permalink,
                        'resolved' => true,
                        'source' => 'post',
                        'object_id' => (int) $post_id,
                    ];
                }
            }

            if (!$resolved['resolved']) {
                $archives = baa_archive_map();

                if (isset($archives[$cache_key])) {
                    $archive = $archives[$cache_key];
                    $label = apply_filters('baa_post_type_label', $archive['label'], $archive['post_type']);
                    $resolved = [
                        'label' => (string) $label,
                        'url' => $url,
                        'resolved' => true,
                        'source' => 'post-type-archive',
                        'object_id' => 0,
                    ];
                }
            }

            if (!$resolved['resolved']) {
                $taxonomies = get_taxonomies(['public' => true], 'names');
                $terms = $taxonomies
                    ? get_terms([
                        'taxonomy' => array_values($taxonomies),
                        'slug' => sanitize_title(rawurldecode($segment)),
                        'hide_empty' => false,
                    ])
                    : [];

                if (!is_wp_error($terms)) {
                    foreach ($terms as $term) {
                        $term_url = get_term_link($term);

                        if (!is_wp_error($term_url) && baa_normalize_url((string) $term_url) === $cache_key) {
                            $resolved = [
                                'label' => (string) $term->name,
                                'url' => (string) $term_url,
                                'resolved' => true,
                                'source' => 'term',
                                'object_id' => (int) $term->term_id,
                            ];
                            break;
                        }
                    }
                }
            }

            if (!$resolved['resolved']) {
                $resolved['label'] = ucwords(str_replace(['-', '_'], ' ', rawurldecode($segment)));
            }

            $base_cache[$cache_key] = $resolved;
        }

        $resolved = apply_filters(
            'baa_resolve_permalink_segment',
            $resolved,
            $url,
            $segment,
            $context
        );

        if (!is_array($resolved) || empty($resolved['label'])) {
            $resolved = [
                'label' => ucwords(str_replace(['-', '_'], ' ', rawurldecode($segment))),
                'url' => null,
                'resolved' => false,
                'source' => 'fallback',
                'object_id' => 0,
            ];
        }

        if (empty($resolved['resolved'])) {
            $resolved['url'] = null;
        }

        return $resolved;
    }
}

if (!function_exists('baa_build_permalink_items')) {
    function baa_build_permalink_items(array $args): array {
        $segments = baa_match_singular_canonical_segments(baa_request_segments());

        if (!$segments) {
            if (!empty($args['show_current'])) {
                $label = baa_current_query_label();
                return $label !== ''
                    ? [baa_item($label, null, true, is_singular(), false, true, 'current-query')]
                    : [];
            }

            return [];
        }

        $items = [];
        $path = [];
        $last_index = count($segments) - 1;
        $current_label = baa_current_query_label();
        $context = [
            'queried_object_id' => (int) get_queried_object_id(),
            'query_object' => get_queried_object(),
            'args' => $args,
        ];

        foreach ($segments as $index => $segment) {
            $path[] = $segment;
            $url = home_url('/' . implode('/', $path) . '/');
            $is_last = $index === $last_index;

            if ($is_last && empty($args['show_current'])) {
                continue;
            }

            $resolved = baa_resolve_permalink_segment($url, $segment, $context);
            $label = $is_last && $current_label !== ''
                ? $current_label
                : (string) $resolved['label'];

            $items[] = baa_item(
                $label,
                $is_last ? null : ($resolved['url'] ?? null),
                $is_last,
                $is_last && is_singular(),
                false,
                !empty($resolved['resolved']),
                $is_last ? 'current-query' : (string) ($resolved['source'] ?? '')
            );
        }

        return $items;
    }
}

if (!function_exists('baa_render_schema')) {
    function baa_render_schema(array $items): string {
        $schema_items = [];

        foreach ($items as $index => $item) {
            $schema_item = [
                '@type' => 'ListItem',
                'position' => $index + 1,
                'name' => wp_strip_all_tags((string) $item['label']),
            ];

            if (!empty($item['url'])) {
                $schema_item['item'] = esc_url_raw((string) $item['url']);
            }

            $schema_items[] = $schema_item;
        }

        if (!$schema_items) {
            return '';
        }

        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => $schema_items,
        ];

        return '<script type="application/ld+json">' .
            wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) .
            '</script>';
    }
}

if (!function_exists('baa_render_label_content')) {
    function baa_render_label_content(string $label, array $item, array $args): string {
        if (empty($item['is_home'])) {
            return esc_html($label);
        }

        $content = '';
        $has_home_icon = false;
        $hide_home_label = !empty($args['hide_home_label']);

        if (!empty($args['show_home_icon']) && !empty($args['home_icon_url'])) {
            $icon_class = $hide_home_label
                ? 'baa__home-icon baa__home-icon--label-hidden'
                : 'baa__home-icon';
            $icon_style = $hide_home_label ? 'margin-inline-end:0' : '';
            $icon = baa_inline_svg((string) $args['home_icon_url'], $icon_class, $icon_style);

            if ($icon !== '') {
                $content .= $icon;
                $has_home_icon = true;
            }
        }

        $label_class = 'baa__home-label';

        if ($has_home_icon && $hide_home_label) {
            $label_class .= ' baa__sr-only';
        }

        $label_style = $has_home_icon && $hide_home_label
            ? 'position:absolute!important;width:1px!important;height:1px!important;padding:0!important;margin:-1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;clip-path:inset(50%)!important;white-space:nowrap!important;border:0!important'
            : '';
        $label_style_attr = $label_style !== '' ? ' style="' . esc_attr($label_style) . '"' : '';

        return $content . '<span class="' . esc_attr($label_class) . '"' . $label_style_attr . '>' . esc_html($label) . '</span>';
    }
}

if (!function_exists('baa_render_separator')) {
    function baa_render_separator(array $args): string {
        if (!empty($args['show_separator_icon']) && !empty($args['separator_icon_url'])) {
            $svg = baa_inline_svg((string) $args['separator_icon_url'], 'baa__separator-icon');

            if ($svg) {
                return $svg;
            }
        }

        return esc_html((string) $args['separator']);
    }
}

if (!function_exists('baa_render')) {
    function baa_render(array $args = []): string {
        $args = wp_parse_args($args, [
            'class' => '',
            'style' => '',
            'aria_label' => 'Breadcrumbs',
            'separator' => '/',
            'trail_source' => 'context',
            'show_home' => true,
            'show_home_icon' => false,
            'hide_home_label' => false,
            'home_icon_url' => '',
            'show_parents' => true,
            'show_post_type' => true,
            'taxonomy_archive_post_type' => '',
            'show_taxonomy' => false,
            'taxonomy' => '',
            'show_current' => true,
            'show_separator_icon' => false,
            'separator_icon_url' => '',
            'enable_schema' => true,
            'home_label' => __('Home', 'baa'),
            'current_title_max_length' => 0,
        ]);

        $items = [];

        if (!empty($args['show_home'])) {
            $items[] = baa_item(
                (string) $args['home_label'],
                is_front_page() ? null : home_url('/'),
                is_front_page(),
                false,
                true,
                true,
                'home'
            );
        }

        if (!is_front_page()) {
            $trail_items = baa_trail_source($args['trail_source']) === 'permalink'
                ? baa_build_permalink_items($args)
                : baa_build_context_items($args);
            $items = array_merge($items, $trail_items);
        }

        $context = [
            'trail_source' => baa_trail_source($args['trail_source']),
            'queried_object_id' => (int) get_queried_object_id(),
            'query_object' => get_queried_object(),
        ];
        $items = apply_filters('baa_breadcrumb_items', $items, $context, $args);
        $items = is_array($items) ? baa_dedupe_items($items) : [];

        if (!$items) {
            return '';
        }

        $extra_class = str_replace('breadcrumbs-appia-antica', '', trim((string) $args['class']));
        $nav_class = trim('breadcrumbs-appia-antica ' . $extra_class);
        $style = trim((string) $args['style']);
        $style_attr = $style ? ' style="' . esc_attr($style) . '"' : '';

        ob_start();
        ?>
        <nav class="<?php echo esc_attr($nav_class); ?>" aria-label="<?php echo esc_attr((string) $args['aria_label']); ?>"<?php echo $style_attr; ?>>
            <ol class="baa__list">
                <?php foreach ($items as $index => $item): ?>
                    <?php
                    $is_link = !empty($item['url']) && empty($item['current']);
                    $label = (string) $item['label'];
                    $title_attr = '';

                    if (!empty($item['is_current_post']) && (int) $args['current_title_max_length'] > 0) {
                        [$short_label, $was_truncated] = baa_truncate(
                            $label,
                            (int) $args['current_title_max_length']
                        );

                        if ($was_truncated) {
                            $title_attr = ' title="' . esc_attr($label) . '"';
                            $label = $short_label;
                        }
                    }

                    $label_content = baa_render_label_content($label, $item, $args);
                    ?>
                    <li class="baa__item"<?php echo !empty($item['current']) ? ' aria-current="page"' : ''; ?>>
                        <?php if ($index > 0): ?>
                            <span class="baa__separator" aria-hidden="true">
                                <?php echo baa_render_separator($args); ?>
                            </span>
                        <?php endif; ?>

                        <?php if ($is_link): ?>
                            <a class="baa__link" href="<?php echo esc_url((string) $item['url']); ?>">
                                <?php echo $label_content; ?>
                            </a>
                        <?php else: ?>
                            <span class="baa__current"<?php echo $title_attr; ?>>
                                <?php echo $label_content; ?>
                            </span>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ol>
        </nav>
        <?php

        $html = trim((string) ob_get_clean());

        if (!empty($args['enable_schema'])) {
            $html .= "\n" . baa_render_schema($items);
        }

        return $html;
    }
}

if (!function_exists('baa_render_marker')) {
    function baa_render_marker(array $matches): string {
        $attrs = shortcode_parse_atts($matches[1] ?? '');
        $attrs = is_array($attrs) ? $attrs : [];

        $get = function (string $key, string $default = '') use ($attrs): string {
            if (!isset($attrs[$key])) {
                return $default;
            }

            return trim(html_entity_decode(
                (string) $attrs[$key],
                ENT_QUOTES,
                get_bloginfo('charset')
            ));
        };

        return baa_render([
            'class' => $get('class'),
            'style' => $get('style'),
            'aria_label' => $get('data-baa-aria-label', 'Breadcrumbs'),
            'separator' => $get('data-baa-separator', '/'),
            'trail_source' => baa_trail_source($get('data-baa-trail-source', 'WordPress Context')),
            'show_home' => baa_bool($get('data-baa-show-home'), true),
            'show_home_icon' => baa_bool($get('data-baa-show-home-icon'), false),
            'hide_home_label' => baa_bool($get('data-baa-hide-home-label'), false),
            'home_icon_url' => esc_url_raw($get('data-baa-home-icon-url')),
            'show_parents' => baa_bool($get('data-baa-show-parents'), true),
            'show_post_type' => baa_bool($get('data-baa-show-post-type'), true),
            'taxonomy_archive_post_type' => $get('data-baa-taxonomy-archive-post-type'),
            'show_taxonomy' => baa_bool($get('data-baa-show-taxonomy'), false),
            'taxonomy' => $get('data-baa-taxonomy'),
            'show_current' => baa_bool($get('data-baa-show-current'), true),
            'show_separator_icon' => baa_bool($get('data-baa-show-separator-icon'), false),
            'separator_icon_url' => esc_url_raw($get('data-baa-separator-icon-url')),
            'enable_schema' => baa_bool($get('data-baa-enable-schema'), true),
            'home_label' => $get('data-baa-home-label', 'Home'),
            'current_title_max_length' => (int) $get('data-baa-current-title-max-length', '0'),
        ]);
    }
}

if (!function_exists('baa_replace_markers')) {
    function baa_replace_markers(string $content): string {
        if (strpos($content, 'data-breadcrumbs-appia-antica-root') === false) {
            return $content;
        }

        $pattern = '/<nav\b([^>]*\sdata-breadcrumbs-appia-antica-root(?:=["\'][^"\']*["\'])?[^>]*)>\s*<\/nav>/i';

        return (string) preg_replace_callback($pattern, 'baa_render_marker', $content);
    }

    add_filter('render_block', 'baa_replace_markers', 20);
    add_filter('the_content', 'baa_replace_markers', 20);
}

if (!function_exists('baa_add_post_type_labels_to_etch_dynamic_data')) {
    function baa_add_post_type_labels_to_etch_dynamic_data($data, $post_id) {
        if (
            isset($data['post_type']) &&
            is_array($data['post_type']) &&
            !empty($data['post_type']['slug']) &&
            !empty($data['post_type']['singular_label']) &&
            !empty($data['post_type']['plural_label'])
        ) {
            return $data;
        }

        $post_type = $data['type'] ?? get_post_type($post_id);

        if (!$post_type) {
            return $data;
        }

        $object = get_post_type_object($post_type);

        if ($object && !empty($object->labels)) {
            $data['post_type'] = [
                'slug' => esc_html($post_type),
                'singular_label' => esc_html($object->labels->singular_name ?? ''),
                'plural_label' => esc_html($object->labels->name ?? ''),
            ];
        }

        return $data;
    }

    add_filter('etch/dynamic_data/post', 'baa_add_post_type_labels_to_etch_dynamic_data', 20, 2);
}
PHP

How it works

Appia Breadcrumbs can build a trail from WordPress content relationships or directly from the current URL. It works with pages, posts, custom post types, taxonomies, custom relationships, and rewritten permalink structures.

It does not require Meta Box or a glossary post type. Those are examples of systems that can provide custom relationships and URLs.

Trail source options

The Trail Source setting controls how Appia builds the breadcrumb trail.

WordPress Context

This mode uses the current WordPress query and its content relationships. Depending on the component settings, the trail can include:

  • The home page
  • A post-type archive
  • Parent pages or hierarchical posts
  • Taxonomy terms and their parents
  • The current post, page, archive, or term

This mode works well when the breadcrumb hierarchy matches the standard WordPress content structure.

Permalink Path

This mode uses the public URL as the breadcrumb hierarchy. It is useful when rewrite rules arrange content differently from the standard WordPress structure.

For example, a custom URL might place a listing under its assigned category instead of its post-type archive:

/destinations/europe/rome-hotel/

Appia reads the path and builds:

Home / Destinations / Europe / Rome Hotel

Parent, post-type, and taxonomy switches are hidden in this mode because the URL already defines the order.

How Permalink Path builds the trail

1. It reads the requested path

Appia removes the site address, query string, and trailing slash. It then splits the remaining path into segments.

/destinations/europe/rome-hotel/

becomes:

destinations
europe
rome-hotel

2. It builds a URL for each level

Appia constructs each cumulative URL:

/destinations/
/destinations/europe/
/destinations/europe/rome-hotel/

3. It resolves each segment

For every cumulative URL, Appia checks for a matching WordPress object. It can recognize:

  • Posts, pages, and custom post-type posts
  • Post-type archives
  • The WordPress posts page
  • Categories, tags, and public taxonomy terms
  • Registered custom post-type names and rewrite slugs
  • A valid final custom endpoint

When Appia finds an object, it uses the object’s WordPress label and permalink. This produces readable labels instead of simply converting URL slugs into text.

4. It handles unresolved segments safely

An unresolved segment can still appear as a readable label, but Appia does not automatically make it a link. A segment’s presence in a valid page URL does not prove that its shorter cumulative URL also works.

For example, this review post may be valid:

/category-parent/category-child/listing-post/reviews/review-post/

That does not prove this intermediate URL has its own route:

/category-parent/category-child/listing-post/reviews/

The rewrite code that owns the nested route can confirm the Reviews URL through an Appia filter. This prevents broken breadcrumb links.

5. It marks the final item as current

The last breadcrumb uses the current post, page, term, archive, or endpoint label. It has no link and receives the current-page accessibility markup.

Common URL structures

Hierarchical pages

/services/design/web-design/
Home / Services / Design / Web Design

Taxonomy and custom post type

/locations/italy/rome-hotel/
Home / Locations / Italy / Rome Hotel

Relationship-based content

A custom relationship can place one post type beneath another:

/listings/grand-hotel/reviews/excellent-stay/
Home / Listings / Grand Hotel / Reviews / Excellent Stay

The relationship plugin can be Meta Box, ACF, Pods, Toolset, custom fields, or custom PHP. Appia only needs WordPress to receive the final URL and load the correct content.

Glossary example

A glossary entry can sit beneath the glossary to which it belongs:

/glossary/web-terminology/cascading-style-sheets/
Home / Glossaries / Web Terminology / Cascading Style Sheets

In this example, Meta Box stores the relationship and a rewrite snippet creates and resolves the URL. Appia reads the resulting path. The same process works with other post types and relationship systems.

Custom endpoints

A rewrite can add a view, filter, tab, letter, or other endpoint to an existing post URL:

/glossary/web-terminology/h/
Home / Glossaries / Web Terminology / H

Appia keeps the endpoint when WordPress loads it as a valid extension of the canonical post URL. Single-letter endpoints are capitalized automatically.

WordPress feeds, embeds, trackbacks, comment pagination, and /page/N/ pagination stay out of the trail by default.

Supporting custom rewrite systems

Appia automatically handles normal WordPress objects and valid final endpoints. Arbitrary intermediate routes need confirmation from the rewrite code that registered them.

The baa_resolve_permalink_segment filter receives:

  • The current resolution result
  • The cumulative URL
  • The current URL segment
  • Information about the current post and its position in the trail

For example, a review rewrite can confirm its intermediate Reviews route:

add_filter(
    'baa_resolve_permalink_segment',
    function (array $resolved, string $url, string $segment, array $context): array {
        if (
            ($resolved['source'] ?? '') !== 'post-type-segment' ||
            ($resolved['post_type'] ?? '') !== 'review' ||
            ($context['current_post_type'] ?? '') !== 'review' ||
            !empty($context['is_last'])
        ) {
            return $resolved;
        }

        return array_merge($resolved, [
            'url' => $url,
            'resolved' => true,
            'source' => 'custom-rewrite',
        ]);
    },
    10,
    4
);
PHP

The baa_resolve_current_permalink_endpoint filter can replace the automatically generated label for a valid final endpoint.

The baa_include_current_permalink_endpoint filter can include or exclude a known endpoint.

The baa_breadcrumb_items filter can modify the completed trail before Appia renders it.

These filters cover rewrite structures that WordPress cannot identify from the URL alone.

Division of responsibilities

The system keeps content structure, URL routing, and breadcrumb rendering separate.

  • WordPress, a plugin, or custom code defines the content and any relationships.
  • WordPress rewrite rules generate and resolve the public URLs.
  • Appia Breadcrumbs converts those URLs into labels, links, accessible markup, and breadcrumb schema.

Changing a relationship or rewrite system does not require new component controls. The URL and resolver filters provide the required information.

Safety behavior

Appia does not send HTTP requests to test every breadcrumb URL. Doing that during page rendering would add delays and could cause request loops on some servers.

Instead, Appia trusts URLs that WordPress can resolve directly. It leaves uncertain intermediate segments unlinked until the rewrite integration confirms them. This gives standard WordPress content automatic behavior without inventing links for custom routes.

Structured data and accessibility

Appia renders the trail as an ordered list inside a navigation element. The current item receives aria-current="page".

When Hide Home Label is enabled and a Home icon is available, sighted users see only the icon. The renderer keeps the Home label in the link as visually hidden text, so screen readers still announce its purpose. If the icon cannot load, Appia leaves the label visible instead of rendering an empty-looking link.

When schema is enabled, Appia also generates BreadcrumbList JSON-LD from the same resolved items. Visible breadcrumbs and structured data therefore stay in sync.

Maintenance

Visit Settings > Permalinks and save once after adding or changing WordPress rewrite rules. Normal content edits and relationship changes do not require another permalink refresh.