Support » Plugins » Hacks » Display a specific level of a category tree

  • Resolved Pete

    (@perthmetro)


    I’m trying to find a way to display a specific category level of a post.

    For example. I have a post with a hierarchical category tree structure like below…

    Parent cat
    Child cat A
    Child cat B
    Child cat C

    I’m looking for a nifty piece code I can use within the loop that will allow me to display any of the category levels, not all the levels.

    Clear as mud? 🙂

    Thanks heaps – Pete

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter Pete

    (@perthmetro)

    Solution via WP Answers.. http://wpquestions.com/question/showChronoLoggedIn/id/9333

    1. Stick this in your functions.php

    function get_level($category, $level = 0)
    {
        if ($category->category_parent == 0) {
            return $level;
        } else {
            $level++;
            $category = get_category($category->category_parent);
    		return get_level($category, $level);
        }
    }
    function display_cat_level( $level = 0 , $link=false){
    	$cats = get_the_category( );
    	if( $cats ){
    		foreach($cats as $cat){
    			$current_cat_level = get_level($cat);
    			if( $current_cat_level  == $level ){
    				if($link==true) {
    					echo '<a href="'.get_category_link($cat->cat_ID).'">'.$cat->name."</a><br />";
    				} else {
    					echo $cat->name."<br />";
    				}
    			}
    		}
    	}
    }

    2. Use either of these tags to display the category level where X is the level you want to display…

    <?php display_cat_level(X,true); ?>
    <?php display_cat_level(X,true); ?>

    Thread Starter Pete

    (@perthmetro)

    2. Use either of these tags to display the category level where X is the level you want to display…

    <?php display_cat_level(X,true); ?> for the cat level to be linked
    <?php display_cat_level(X); ?>  for the cat level NOT to be linked
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Display a specific level of a category tree’ is closed to new replies.