get_depth()

2010-01-16 @ 14:54

The problem

As far as I know there is no function in WordPress that return the page or category depth.

The solution

I created a function that returns the depth of a page or category. The depth is how many levels from the root the page or category in its hierarchy. The root level number is 0.

function get_depth($id = '', $depth = '', $i = 0)
{
	global $wpdb;

	if($depth == '')
	{
		if(is_page())
		{
			if($id == '')
			{
				global $post;
				$id = $post->ID;
			}
			$depth = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID = '".$id."'");
			return get_depth($id, $depth, $i);
		}
		elseif(is_category())
		{

			if($id == '')
			{
				global $cat;
				$id = $cat;
			}
			$depth = $wpdb->get_var("SELECT parent FROM $wpdb->term_taxonomy WHERE term_id = '".$id."'");
			return get_depth($id, $depth, $i);
		}
		elseif(is_single())
		{
			if($id == '')
			{
				$category = get_the_category();
				$id = $category[0]->cat_ID;
			}
			$depth = $wpdb->get_var("SELECT parent FROM $wpdb->term_taxonomy WHERE term_id = '".$id."'");
			return get_depth($id, $depth, $i);
		}
	}
	elseif($depth == '0')
	{
		return $i;
	}
	elseif(is_single() || is_category())
	{
		$depth = $wpdb->get_var("SELECT parent FROM $wpdb->term_taxonomy WHERE term_id = '".$depth."'");
		$i++;
		return get_depth($id, $depth, $i);
	}
	elseif(is_page())
	{
		$depth = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID = '".$depth."'");
		$i++;
		return get_depth($id, $depth, $i);
	}
}

Function call

Send an ID with the function or it will use current ID to get the depth. Call the function somewhere in your theme.

  • In a category – It will return the depth of the current category, if no ID is sent.
  • In a page – It will return the depth of the current page, if no ID is sent.
  • In a post – It will return the depth of the first category assigned to the post, if no ID is sent.
<?php echo get_depth(); ?>
<?php echo get_depth(2); ?>

Alternative (for page depth only)

Here comes a much shorter alternative if you only need to get the depth of pages. This works on page.php. If you are using it in other places, make sure the $post variable are correct.

<?php echo count($post->ancestors); ?>

Alternative (for category depth only)

This code works with archive.php or category.php. If you are using another template file, you need to insert the category ID into the $cat variable.

<?php
$cats_str = get_category_parents($cat, false, '%#%');
$cats_array = explode('%#%', $cats_str);
$cat_depth = sizeof($cats_array)-2;
echo $cat_depth;
?>

Contributors

Improvements

Do you have any ideas, bugs, features or anything else to improve the code? Write a comment and I’ll look into it.

Other solutions

Share
RSS-feed for comments

17 replys to “get_depth()”

Leave a reply