You need to get the comment ID from the URL and then you can look up the post. So imagine you have this:
https://example.com/2016/07/09/post-name/#comment-12
The comment ID is 12. You’d need to extract that from the string. Stuff like preg_replace()
or filter_var()
can be used here. Once you have the comment ID you can do this:
$comment = get_comment( $comment_id );
echo get_permalink( $comment->comment_post_ID );
Thanks Henry.
I actually had worked out that function by going through some BuddyPress code, but it’s the first part that’s holding me up. Exactly how do I use preg_replace or filter_var to extract the comment ID?
It strikes me that preg_replace could be used to simply remove the comment ID from the post URL, which may be an even simple way of doing it, but once again I don’t know how to implement this.
preg_replace() requires a pattern, a replacement and a source string. In your case the source string will be your comment URL. Try this:
$url = 'https://example.com/2016/07/09/post-name/#comment-12';
$pattern = '/#comment-([0-9]+)/';
$replacement = '$1';
$comment_id = preg_replace( $pattern, $replacement, $url );
Ref: http://php.net/manual/en/function.preg-replace.php
Ah I see, I think I’ve got it now – thanks Henry!
A bit different method is explained here.
Thanks danbp, that looks very useful.
Hi @danbp
We have just the comment URL to start with so the method you linked to won’t work.
@henrywright, ah ?
OK, thx for the lesson 🙂