how to get the comment ID in the front end when the REPLY button is clicked?

I think I might be able to parse the URL for the replytocom parameter and get the comment ID from that. However, it would mean that my plugin would not be fully compatible with other plugins that can remove this parameter (most notably Yoast SEO). Plus, it feels a bit hacky. Is there another way?

Endgoal: I need that comment ID to use in an AJAX request – to fetch data (such as the comment thread depth) so that I can display custom data in the front end.

Solutions Collecting From Web of "how to get the comment ID in the front end when the REPLY button is clicked?"

Here are few ideas:

  • It’s possible to inject custom HTML or data attributes via the comment_reply_link filter, but I think it would be better to keep it unobtrusive.

  • One could try to get the comment parent value from the reply comment form:

    <input type='hidden' name='comment_parent' id='comment_parent' value='0' />

    after it has been updated with the corresponding value.

  • Another approach would be to scan for IDs in the HTML of the comments list:

    Generated by the Walker_Comment::html5_comment():

    <li id="comment-34" class="comment even thread-even depth-1">
        <article id="div-comment-34" class="comment-body">
        ... cut...

    Generated by the Walker_Comment::comment():

    <li class="comment even thread-even depth-1 parent" id="comment-34">
        <div id="div-comment-34" class="comment-body">
        ... cut...

    One could e.g. search for both cases, but it’s possible for the user to override these with a custom output.

    Also note the depth information here.

  • One could try to parse the onclick attribute of the replyto link:

    onclick='return addComment.moveForm( "div-comment-34", "34", "respond", "123" )'

This is my implementation of birgire’s last suggestion (to parse the onclick):

jQuery(document).on( 'click', 'a.comment-reply-link', function( event ) {

var hayStack = jQuery(this).attr('onclick');
var strawA = '"div-comment-';
var strawB = '"';
var tipNeedle = hayStack.lastIndexOf(strawA)+strawA.length;
var hayTruss = hayStack.substring(tipNeedle);
var endNeedle = hayTruss.indexOf(strawB); 
var needle = hayTruss.substring(0, endNeedle);

// optional: THIS PART LOOKS UP THE PARENT ID (php side not shown)
var datatopost = {
        action: 'my_ajax_hook',
        nonce: ajaxobject.nonce,
        selected_comment_id: needle,
    type: 'post',
    dataType: 'json',
    url: ajaxobject.ajaxurl,
    data: datatopost,
    error: function() { // Ajax request has failed
        jQuery('#comment').val('An error has occurred');
    success: function (response) { // Ajax request has succeeded
        if (response.success) {
            // JSON successfully received