Checking if the current term in a Bricks Terms query loop of the given taxonomy has children

There could be situations when you need a way to check if the current term in a Bricks Terms query loop has children or not.

This Pro tutorial shows how.

Sample query loop:

Step 1

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php

// Function to check if the current term (in a Terms query loop) of the given taxonomy has children
function bl_current_loop_term_has_children( $taxonomy = 'category' ) {
	$term_children = get_term_children( BricksQuery::get_loop_object_id(), $taxonomy );

	return count( $term_children ) > 0;
}

Step 2

Whitelist the bl_current_loop_term_has_children function.

Ex.:

<?php 

add_filter( 'bricks/code/echo_function_names', function() {
  return [
    'bl_current_loop_term_has_children'
  ];
} );

You should also add any other functions (native or custom) being used in your Bricks instance in addition to bl_current_loop_term_has_children. This can be checked at Bricks → Settings → Custom code by clicking the Code review button.

More info on whitelisting can be found here.

Step 3

You can now use the dynamic data tag:

{echo:bl_current_loop_term_has_children(service-type)}

where service-type is the taxonomy key/ID.

If the taxonomy is category, then there’s no need to supply the argument.

{echo:bl_current_loop_term_has_children}

Note: This condition will not work for the query-loop enabled element. It will only work for any element that is inside the query loop. Therefore, if you are looking to output only the terms that have at least 1 child term you should group all the elements inside the query loop in a Container and apply the condition on that Container.

Reference

https://brickslabs.com/function-current-term-has-children/