• Resolved Martin

    (@martinlucas)


    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;

    Cushion
    – Colours
    – – Blue
    – – Red
    – Themes
    – – Children’s
    – – Seaside
    Curtain
    – 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!

Viewing 3 replies - 1 through 3 (of 3 total)
  • 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
    
    }
    Thread Starter Martin

    (@martinlucas)

    Works a treat, thank you so much!

    wp_list_categories(‘taxonomy=product_cat&orderby=order&title_li=&depth=1’);
    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;
    }
    }
    ?>

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘If current taxonomy has child and/or parent’ is closed to new replies.