0

Let's say that this is the comment link:

http://localhost/post/test/#comment-86

I want to do this thing:

  • Check if current page URL requesting a comment or not (have #comment-x or not).

  • If current page URL is requesting a comment get the comment id from the URL.

  • With pure PHP you can't (see this answer or this one) – kero Apr 13 '18 at 16:24
  • @kero Let me explain what I need to do, I want to make when opens a comment link get the comment id from the link to appear a popup modal of the comment content so my problem that I can't get the requested comment id, can you advise me how can get the requested comment? – Mido Apr 13 '18 at 18:12
2

Based on your comment, you can get the comment ID via JavaScript, and here's a sample function you can use/try:

<script>
function getCommentIdFromUrl( url ) {
    return (
        ( url && /#comment-(\d+)$/.test( url ) ) ||
        ( location.hash && /^#comment-(\d+)$/.test( location.hash ) )
    ) && RegExp.$1;
}
</script>

So if the URL of the current page is http://example.com/hello-world/#comment-76, getCommentIdFromUrl() would return 76.

Alternatively, you could ignore the above function and use the second expression with a variable, like so:

var comment_ID = location.hash && /^#comment-(\d+)$/.test( location.hash ) && RegExp.$1;

Hope that helps.

[EDIT] In reply to your comment on my answer, you can ignore all the above code, and use this instead:

var
    // Check if the current URL ends with a #comment-123, where 123 is the comment ID.
    is_comment_link = /#comment-(\d+)$/.test( location.href ),

    // Removes the #comment- portion from the URL hash, and get the comment ID.
    comment_ID = is_comment_link && location.hash.substring(9);

Or you could also use:

var is_comment_link, comment_ID;

if ( /#comment-(\d+)$/.test( location.href ) ) {
    is_comment_link = true;
    comment_ID = RegExp.$1;
}
  • Thank you but can you add also an if condition to check if the URL is a comment link or not? (Javascript). – Mido Apr 14 '18 at 6:41
  • I've updated the answer. Check it out. – Sally CJ Apr 14 '18 at 8:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.