WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] category level (5 posts)

  1. elotse
    Member
    Posted 3 years ago #

    How can I get the level of the category.
    I wont to control some function based on the category level

  2. elotse
    Member
    Posted 3 years ago #

    Sorry, I am looking for a php code (reed) not just to see the level
    Example: get_the_category_level ????

  3. Mark / t31os
    Moderator
    Posted 3 years ago #

    Maybe?
    http://codex.wordpress.org/Function_Reference/get_category_parents

    You could work out the level based on what's returned.

    Something like..

    $parents = get_category_parents( YOURCATIDHERE , false, '|' );
    $levels = '';
    if( $parents ) {
    	if( false != strpos( $parents , '|' ) )
    		$levels = count( explode( '|' , $parents ) );
    	else
    		$levels = 1;
    }
    echo $levels;
  4. MichaelH
    Member
    Posted 3 years ago #

    Might also see if this helps:

    <?php
    //test category 11 depth or level
    $max_depth_to_test = intval(9); //set this to highest depth you might have
    $last_depth = 0;
    $cat_to_test = 11;
    $category=get_category($cat_to_test);
    for ( $counter = 1; $counter <= $max_depth_to_test; $counter += 1) {
      if ($category->category_parent) {
        $category=get_category($category->category_parent);
        $last_depth = $counter;
      }
    }
    $last_depth +=1;
    echo '<p>Category ' . $cat_to_test . ' it is at depth ' . $last_depth .'</p>';
    ?>
  5. elotse
    Member
    Posted 3 years ago #

    @MichaelH
    Your code is exactly the solution I am looking for, thank you

Topic Closed

This topic has been closed to new replies.

About this Topic