Skip to:
Content
Pages
Categories
Search
Top
Bottom

How to get a blog post link from a comment link


  • ljmac
    Participant

    @ljmac

    Hi,

    A quick and simple one: assuming that I have a permalink for a blog comment, how do I get the permalink for the comment’s blog post from it?

Viewing 8 replies - 1 through 8 (of 8 total)

  • Henry Wright
    Moderator

    @henrywright

    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 );

    ljmac
    Participant

    @ljmac

    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.


    Henry Wright
    Moderator

    @henrywright

    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


    ljmac
    Participant

    @ljmac

    Ah I see, I think I’ve got it now – thanks Henry!


    danbp
    Participant

    @danbp

    A bit different method is explained here.


    ljmac
    Participant

    @ljmac

    Thanks danbp, that looks very useful.


    Henry Wright
    Moderator

    @henrywright

    Hi @danbp

    We have just the comment URL to start with so the method you linked to won’t work.


    danbp
    Participant

    @danbp

    @henrywright, ah ?

    OK, thx for the lesson 🙂

Viewing 8 replies - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.
Skip to toolbar