php – WordPress get_the_term_list include class name for heirachy

Question

I have a custom post type which uses custom categories (taxonomy) – called project-type with 2 levels of heirachy which are tagged to different posts.

When viewing the custom post page I want a way to be able to render the custom categories it is tagged with – I have this working using get_the_term_list as per code below:

<?php
$the_terms = get_the_term_list( get_the_id(), 'project-type', __( "" ) . "<li>", "<span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li><li>", "<span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>" );
?>
<ul>
<li><a href="/projects/">PROJECTS</a><span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>
<?php echo $the_terms; ?>
</ul>

This works well, BUT… what I want to be able to do is add an identifier – class name or ID to the <li> based on its heirachy within the custom categories I am using.

So for the top level categories the post is tagged with, id like to add “level1” class to the LI and for the 2nd level categories the post is tagged with we add “level2” class to the LI.

So for example: Custom categories:

Cat Parent A
    Cat Child AA
    Cat Child AB
Cat Parent B
    Cat Child BA
    Cat Child BB

And if the custom post was tagged with Cat Parent A and Cat Child AB – then the current output of the terms fetched would be:

<ul>
<li><a href="/projects/">PROJECTS</a><span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>
<li><a href="/slug/">Cat Parent A</a><span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>
<li><a href="/slug/">Cat Child AB</a><span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>
</ul>

My desired outcome with the addition of these classes would be:

<ul>
<li><a href="/projects/">PROJECTS</a><span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>
<li class="level1"><a href="/slug/">Cat Parent A</a><span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>
<li class="level2"><a href="/slug/">Cat Child AB</a><span class="sf-sub-indicator"><i class="fa fa-angle-right icon-in-menu" aria-hidden='true'></i></span></li>
</ul>

How can I achieve this?

0
dubbs 1 week 2022-11-19T02:49:36-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse