Using WordPress ‘comment_id_fields()’ PHP function

The comment_id_fields() WordPress PHP function outputs hidden input HTML for replying to comments. It adds two hidden inputs to the comment form in order to identify the comment_post_ID and comment_parent values for threaded comments. This function needs to be used within the <form> section of the comments.php template.

Usage

To use the comment_id_fields() function, call it within the comment form in your comments.php template file. The function can take a post ID or a WP_Post object as a parameter, but it’s optional. If no parameter is given, it defaults to the current global post.

comment_id_fields($post_id);

Parameters

  • $post (int|WP_Post|null) (Optional) – The post the comment is being displayed for. Defaults to the current global post. Default is null.

More information

See WordPress Developer Resources: comment_id_fields()

This function is a core part of WordPress, meaning it’s used in many themes and plugins that require comment functionality. It’s important to note that if you’re building a custom comment form, you’ll need to ensure this function is included to properly thread comments.

Examples

Basic usage in a comment form

In this example, we’re using comment_id_fields() in a basic comment form. The function will add the necessary hidden fields for comment threading.

<form method="post">
    <!-- Your comment fields go here -->
    <?php comment_id_fields(); ?>
    <input type="submit" value="Post Comment">
</form>

Using with a specific post

Here, we’re specifying a post by passing its ID to the comment_id_fields() function.

<form method="post">
    <!-- Your comment fields go here -->
    <?php comment_id_fields(42); ?>
    <input type="submit" value="Post Comment">
</form>

Using within a loop

This example shows how to use the function within the Loop, which automatically passes the current post to the function.

while (have_posts()) : the_post();
    <form method="post">
        <!-- Your comment fields go here -->
        <?php comment_id_fields(); ?>
        <input type="submit" value="Post Comment">
    </form>
endwhile;

Using with a WP_Post object

In this case, we’re using a WP_Post object as the parameter for the comment_id_fields() function.

$post_object = get_post(42);
<form method="post">
    <!-- Your comment fields go here -->
    <?php comment_id_fields($post_object); ?>
    <input type="submit" value="Post Comment">
</form>

Checking if it’s a single post page

Here, we’re only displaying the comment form with comment_id_fields() if it’s a single post page.

if (is_single()) :
    <form method="post">
        <!-- Your comment fields go here -->
        <?php comment_id_fields(); ?>
        <input type="submit" value="Post Comment">
    </form>
endif;