Aleš Sýkora / November 28, 2023 / 0 comments

How to check if product category has child terms on term archive page?

Post summary: If you want to display or hide some content on WooCommerce product category archive page based on if it has child terms, then you will need to check if current category archive term, has a childs.

If you want to display or hide some content on WooCommerce product category archive page based on if it has child terms, then you will need to check if current category archive term, has a childs.

You can use this code in your template or in known builders. Today I will show it with Bricks builder conditional, but it’s also usable in Oxygen builder and others.

PHP Function

What this function do?

  1. Get current queried object and save it to the variable called $term
  2. Create variable $term_id with current term id
  3. Create varible $taxonomy_name which stores slug of taxonomy (in this case it’s product_cat)
  4. Create variable $terms which result of get_term_children
  5. if $terms is empty or fall into error, then the whole function returns a text has_child.
<?php
function check_parent_child_term()
{
    $term = get_queried_object();  
    $term_id = $term->term_id;
    $taxonomy_name = 'product_cat'; //you can change to custom Tax
    $terms = get_term_children( $term_id, $taxonomy_name );

    if ( !empty( $terms ) && !is_wp_error( $terms ) ){
        return "has_child"; //you can change to echo, if you want to test it
    }
    
}
?>

How to use this with Bricks Builder?

If you want to use this function in Bricks Builder conditional, then you must add function into your WordPress installation (you can use Advanced Scripts). After that, you can simply use it like this:

When creating the conditional, select the Dynamic data > Output PHP function

Then add the name of function after the echo: like this:

And you are done. Your section will now display only if current product category has child terms.

Bonus – check if current term is top level parent

If you just want to check if current terms parent is 0 (it doesn’t have parent) then use this function check_if_has_parent().

<?php
function check_if_has_parent()
{
    $term = get_queried_object();
    if ($term->parent == 0) {
        return "parent";
    }  
}
?>

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

0 comments

Share Your Thoughts