Tuesday, March 21, 2023
The Great Tit
Updated: 21. 3. 2023, Added: 21. 3. 2023

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

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: {echo:check_parent_child_term}

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";
    }  
}
?>
Did I help you? Support me on Patreon!
Beep this article to your friends!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram