How to get values from a comment

Last updated Mar 16, 2015

Overview

To display custom field values within comments, you will need to setup a custom callback function for the wp_list_comments() function. This is well explained in an article Creating a custom comment list.

All template functions can be used with a comment, however, a second parameter is required to target the specific comment. This is similar to passing through a $post_id value to target a specific post object.

The second parameter can be given in either of 2 formats:

Comment Object

The comment object can be passed as the $post_id parameter. This is the most simple way to load a value from a comment object. You will be passed a comment object when using a custom callback for the wp_list_comments() function.

Comment String

The comment string can be passed as the $post_id parameter and is constructed from the comment’s ID. In code, this looks like "comment_{$comment->comment_ID}"

Requirements

Custom fields for comments requires at least ACF version 5

Examples

Basic parameter use

This example shows how the second parameter is used to target the specific comment.

<p><?php the_field('field_name', $comment); ?></p>

Custom comment list

This example shows how to create a custom comment list callback and display some custom fields.

single.php

<?php comments_template(); ?>

comments.php

<?php

wp_list_comments(array(
    'callback'    => 'my_comment_template'
));

?>

functions.php

<?php

function my_comment_template( $comment, $args, $depth ) {
    
    ?>
    <div class="comment">
        
        <?php if( get_field('upload_image', $comment) ): ?>
            
            <img src="<?php the_field('image', $comment); ?>" />
            
        <?php endif; ?>
    
    </div>
    
    <?php
}

?>

Related