WordPress Code to display categories like this

I’m currently struggling with displaying custom taxonomy terms in a WordPress theme, and I can’t seem to get the desired output. I’m using a custom taxonomy called genre, which is attached to a custom post type. The problem is how I need to display the taxonomy terms on a single post page.

Desired Output:

I need to display parent categories with their subcategories in the following format:

Fiction (Cyberpunk, Timepunk (Steampunk/Paropunk)) | Fantasy (Heroic Fantasy)

The Problem:

At the moment, I’m using the following code in my functions.php file to generate the output:

function get_taxonomy_output($terms) {
    if (!is_wp_error($terms) && !empty($terms)) {
        $parent_cats = array();
        $child_cats = array();

        // Sort categories into parent and child categories
        foreach ($terms as $term) {
            if ($term->parent == 0) {  // This is the parent category
                $parent_cats[$term->term_id] = $term;
            } else {  // This is a child category
                $child_cats[$term->parent][] = $term;
            }
        }

        // Form the output line
        $output = array();
        foreach ($parent_cats as $parent_id => $parent_cat) {
            $output[] = build_category_output($parent_cat, $child_cats);
        }

        return implode(', ', $output);
    }
    return '';
}

function build_category_output($parent_cat, $child_cats) {
    $parent_link = '<a href="' . esc_url(get_term_link($parent_cat)) . '">' . esc_html($parent_cat->name) . '</a>';
    $output = $parent_link;

    if (!empty($child_cats[$parent_cat->term_id])) {
        $children = array();
        foreach ($child_cats[$parent_cat->term_id] as $child_cat) {
            // Check if the current subcategory has its own subcategories
            if (!empty($child_cats[$child_cat->term_id])) {
                $children[] = build_category_output($child_cat, $child_cats); // Recursively build child categories
            } else {
                $children[] = '<a href="' . esc_url(get_term_link($child_cat)) . '">' . esc_html($child_cat->name) . '</a>';
            }
        }
        $output .= ' (' . implode(', ', $children) . ')';
    }
    return $output;
}

And in single.php I have this code

$categories = get_the_terms(get_the_ID(), 'genre');
$output_genre = get_taxonomy_output($categories);

In the place where I want to display subcategories, this is displayed:

Fiction and Fantasy (Fiction (Cyberpunk, Timepunk (Steampunk/Paropunk), Fantasy (Heroic Fantasy)).

It should be like this:

Fiction (Cyberpunk, Timepunk (Steampunk/Paropunk) | Fantasy (Heroic Fantasy)

I attach an image of how it looks in the admin panel.

I am trying to make code that will be as optimized as possible and meet all WordPress development standards.

1

It looks like there is a small issue with get_taxonomy_output function, so could you please try to replace given line of code in that function.

return implode(', ', $output);

with the given code.

return implode(' | ', $output); // Here we are using ' | ' as the separator for parent categories.

It should works for you.

get_taxonomy_output Function:

Uses implode(' | ', $output) to separate parent categories with |.

build_category_output Function:

Recursively builds the output for child categories and maintains proper formatting with parentheses.

Updated Code:

function get_taxonomy_output($terms) {
    if (!is_wp_error($terms) && !empty($terms)) {
        $parent_cats = array();
        $child_cats = array();

        // Sort categories into parent and child categories
        foreach ($terms as $term) {
            if ($term->parent == 0) {  // This is the parent category
                $parent_cats[$term->term_id] = $term;
            } else {  // This is a child category
                $child_cats[$term->parent][] = $term;
            }
        }

        // Form the output line
        $output = array();
        foreach ($parent_cats as $parent_id => $parent_cat) {
            $output[] = build_category_output($parent_cat, $child_cats);
        }

        // Return the output with a ' | ' delimiter
        return implode(' | ', $output);
    }
    return '';
}

function build_category_output($parent_cat, $child_cats) {
    $parent_link = '<a href="' . esc_url(get_term_link($parent_cat)) . '">' . esc_html($parent_cat->name) . '</a>';
    $output = $parent_link;

    if (!empty($child_cats[$parent_cat->term_id])) {
        $children = array();
        foreach ($child_cats[$parent_cat->term_id] as $child_cat) {
            // Check if the current subcategory has its own subcategories
            if (!empty($child_cats[$child_cat->term_id])) {
                $children[] = build_category_output($child_cat, $child_cats); // Recursively build child categories
            } else {
                $children[] = '<a href="' . esc_url(get_term_link($child_cat)) . '">' . esc_html($child_cat->name) . '</a>';
            }
        }
        $output .= ' (' . implode(', ', $children) . ')';
    }
    return $output;
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật