Diwakar Academy

  • Home
  • WordPress
  • About Us
  • Contact Us
You are here: Home / WordPress / 2 Ways to Get Comment Depth

October 11, 2023

2 Ways to Get Comment Depth

Spread the love

2 Ways to Get Comment Depth

Table of Contents

Toggle
  • 1. Get the comment depth by using global variables
  • 2. Get the comment depth by comment ID

1. Get the comment depth by using global variables

You probably know about the “wp_list_comments()” function; it’s what displays comments on a website.

Here’s why it’s useful:

1. This function does more than just show comments. It runs through the comments one by one and keeps track of how deep each comment is in the conversation. It stores this depth information in a global variable.

2. You can also customize the way comments look by using your own comment template. You do this by using a parameter called “callback.” When you use your custom comment template function (like “my_custom_comment_template()”), you can access the comment depth using the global variables “$comment_depth” or “$GLOBALS[‘comment_depth’].”

2. Get the comment depth by comment ID

But what if you don’t have access to the global variable “$comment_depth”? What if all you have is the comment’s ID?

I believe this straightforward function can assist you in that situation:

function diwakar_get_comment_depth( $my_comment_id ) {

                $depth_level = 0;

                while( $my_comment_id > 0  ) { // if you have ideas how we can do it without a loop, please, share it with us in comments

                                $my_comment = get_comment( $my_comment_id );

                                $my_comment_id = $my_comment->comment_parent;

                                $depth_level++;

                }

                return $depth_level;

}

Then: echo diwakar_get_comment_depth( 784 ); // print the depth level of comment 784

Related Articles

  • Better Way to Add Inline Scripts
  • Stay Logged in to WordPress

Article by Diwakar Academy / WordPress Leave a Comment

Leave a Reply Cancel reply

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

  • Home
  • WordPress
  • About Us
  • Contact Us

Copyright © 2025 · All Rights Reserved · Terms and Conditions · Privacy Policy