Function and usage of comment_link() in wordpress


Answers ( 1 )


    The comment_link() function in WordPress is used to display a link to a specific comment within a post or a page. Here's a detailed explanation and sample usage of this function:


    comment_link( int|WP_Comment $comment = null )


    The primary function of comment_link() is to output the URL link to a particular comment. This is useful in templates where you might want to provide a direct link to a comment.


    • $comment (int | WP_Comment) (Optional): This parameter can be either an integer or a WP_Comment object.
      • If it's an integer, it's assumed to be the ID of the comment for which the link is to be displayed.
      • If it's a WP_Comment object, it represents the comment itself.
      • If this parameter is not provided, or if it's null, the function will use the global comment object that WordPress sets up during The Loop.

    Default Value:

    • null: This means that if no argument is provided, the function will default to using the global comment object.

    Sample Usage:

    Scenario 1: Displaying a Link to the Current Comment in The Loop

    if ( have_comments() ) {
        while ( have_comments() ) {
            echo 'Link to this comment: ';

    In this example, during The Loop over the comments (typically in a comments template), comment_link() is used without any parameter, so it defaults to the current comment being processed.

    Scenario 2: Displaying a Link to a Specific Comment by ID

    $comment_id = 123; // Assuming 123 is the ID of the comment
    echo 'Link to comment ID 123: ';
    comment_link( $comment_id );

    Here, comment_link() is used with a specific comment ID. It will display a link to the comment whose ID is 123.

    Scenario 3: Using a WP_Comment Object

    $comment = get_comment( 123 ); // Retrieves the comment object for comment ID 123
    echo 'Link to this comment: ';
    comment_link( $comment );

    In this case, a WP_Comment object is obtained using get_comment() and passed to comment_link(), which then displays a link to that specific comment.


    • The comment_link() function is particularly useful in themes or plugins where a direct link to a comment is needed.
    • It’s important to ensure that the comment ID or the WP_Comment object passed to the function is valid to avoid broken links or errors.

    This function is a part of WordPress's extensive template tag system, which allows theme developers to easily display and manipulate various WordPress elements.

Leave an answer