Taxonomy query for children of parents

I am stuck on this. I thought I had it correct but then realized it’s not.

I have a custom hierarchical taxonomy based on location. States are top level and countries are children. I have the top level states in a right side menu and when chosen take me to the taxonomy page for that state. Within that state page the right hand menu should display the counties for only that particular state. Instead it is retrieving all the children of the states and displaying. Since this is a taxonomy page for the state.

Read More

Is their a query to determine the current top level page and just display the children as links?

My current code is below.

$taxonomyName = "location";
//This gets top layer terms only.  This is done by setting parent to 0.  
$parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false));   
echo '<ul>';
foreach ($parent_terms as $pterm) {
    //Get the Child terms
    $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id,'orderby' => 'slug', 'hide_empty' => false));
    foreach ($terms as $term) {
        echo '<li><h3><a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</h3></a></li>';  
    }
}
echo '</ul>';

Related posts

1 comment

  1. Use get_queried_object() to get the current queried term on a category page:

    $this_term = get_queried_object();
    $args = array(
        'parent' => $this_term->term_id,
        'orderby' => 'slug',
        'hide_empty' => false
    );
    $child_terms = get_terms( $this_term->taxonomy, $args );
    echo '<ul>';
    foreach ($child_terms as $term) {
        echo '<li><h3><a href="' . get_term_link( $term->name, $this_term->taxonomy ) . '">' . $term->name . '</h3></a></li>';  
    }
    echo '</ul>';
    

Comments are closed.