1
votes

I have a custom taxonomy with two levels of terms.

  • Parent term
    • Child term
    • Child term
  • Parent term
    • Child term
    • Child term
  • Parent term (no children)

I'm using a custom archive.php template with some HTML that I only want to display on terms without child terms.

Here's what I've tried...

$taxonomy = 'custom_tax';
$term = get_queried_object();

$children = get_terms( $term->taxonomy, array( 'parent' => $term->term_id ) );

if(!$children) {
    echo '<p>HTML only terms without child terms</p>';
}

This works if it's a Child term but not on a Parent term with no children!

Any help please?

3

3 Answers

3
votes

Set parent to 0 in the get_terms args, will only return top level taxonomy terms:

$terms = get_terms( array( 
    'taxonomy' => 'custom_tax',
    'parent'   => 0
) );

Then you can filter those results based on whether there are child terms or not. This get_term_children function will return an array of child terms:

$term_children = get_term_children( $term_id, $taxonomy_name );
0
votes

So, I ended doing the following which worked perfectly for my situation.

Using $term->term_id returned an empty array so I used get_queried_object_id()

$term_id = get_queried_object_id();

The used the function as recommended above by BugsArePeopleToo

$term_children = get_term_children( $term_id, 'custom_taxonomy' );

To get Parent without children terms I checked if the array returned was empty. If it was then I can show my HTML.

I also checked to see if a term had a Parent by checking the $term->parent ID.

if( empty($term_children) && $term->parent > 0 )

It helped to browse through the terms by echoing the parent ID and printing the array.

echo $term->parent;
print_r($term_children);

Putting it all together:

$term_id = get_queried_object_id();
$term_children = get_term_children( $term_id, 'custom_taxonomy' );

echo $term->parent;
print_r($term_children);

if( empty($term_children) && $term->parent > 0 ) {
    echo "<p>Hello world.</p>";
}
-1
votes
<?php $term = get_queried_object(); ?>

<?php echo $term->name; ?>

<?php 
$children = get_terms( $term->taxonomy, array(
'parent'    => $term->term_id,
'hide_empty' => false
) );
if($children) { 

foreach ( $children as $child ) {
    ?>

    <?php echo '<li>' . $child->name . '</li>'; ?>

    <?php 
        $loop = new WP_Query( array( 
            'orderby' => 'date',
            'order' => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => 'mycustomtaxonomy',
                    'field' => 'id',
                    'terms' => $child->term_taxonomy_id
                )
            )
        ));
        while ($loop->have_posts()) : $loop->the_post();
        ?>

        <?php echo '<div>' . get_the_title() . '</div>'; ?>

        <?php 
        endwhile;
        wp_reset_postdata();
?>

<?php }
} ?>