Ready to get started?Download WordPress


[resolved] If current taxonomy has child and/or parent (4 posts)

  1. Martin
    Posted 1 year ago #

    I have a taxonomy-types.php set up with a custom post type (Products) and on this page I want to display different content depending on what level (hierarchical) taxonomy is currently being displayed, which are like this;

    - Colours
    - - Blue
    - - Red
    - Themes
    - - Children's
    - - Seaside
    - Colours
    - - Purple
    - - Orange

    I have 3 levels of taxonomy (above) and I just need to test whether the current taxonomy has;

    1. Has no parent but has a child (level 1)
    2. Has both a parent and a child (level 2)
    3. Has a parent and no child (level 3)

    This will give me the three different levels and depending on what level the visitor is currently in, I'll display something different on the page.

    I hope that makes sense, any help would be much appreciated. Thank you!

  2. jonnyvaughan
    Posted 1 year ago #

    How about something like this, which uses get_term_by and get_terms to check if the current term has a parent, and then get_term_children to check for children.

    $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); // get current term
    $parent = get_term($term->parent, get_query_var('taxonomy') ); // get parent term
    $children = get_term_children($term->term_id, get_query_var('taxonomy')); // get children
    if(($parent->term_id!="" && sizeof($children)>0)) {
    	// has parent and child
    }elseif(($parent->term_id!="") && (sizeof($children)==0)) {
    	// has parent, no child
    }elseif(($parent->term_id=="") && (sizeof($children)>0)) {
    	// no parent, has child
  3. Martin
    Posted 1 year ago #

    Works a treat, thank you so much!

  4. jaydipsinh.parmar
    Posted 6 months ago #

    this will also get parent category only. procudt_cat is category name
    simple code
    `also simple code is

    $terms = get_terms('product_cat');
    foreach ($terms as $term) {

    if($term->parent == 0 ){
    echo $term->name;

Topic Closed

This topic has been closed to new replies.

About this Topic