Page or post depth in wordpress

Sometimes we need to get depth of posts or pages in wordpress. Now you can do it easy with function


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

Copy function getDepth() in your function.php file. Call it from your template, for example <?php echo getDepth($post_ID);?>

and it will return your post depth in your site.

Try, I hope it will help you.

2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *