0

In the latest version of WordPress, if I added the following code to include a custom field to my functions.php file...

function add_comment_fields($fields) {
    $fields['source'] = '<p class="comment-form-source ast-col-xs-12 ast-col-sm-12 ast-col-md-4 ast-col-lg-4"><label for="source" class="screen-reader-text">' . __( 'Related Publishing Source' ) . '</label>' .
        '<input id="source" name="source" type="text" value="" placeholder="Publishing Source" size="30" aria-required="true" /></p>';
    return $fields;
}
add_filter('comment_form_default_fields','add_comment_fields');

...how do I "display the results" of this custom field onto the comments page for each comment posted?

I was looking at the get_comments function, with an example like so....

<?php
$args = array(
    'user_id' => 1, // use user_id
);
$comments = get_comments( $args );
 
foreach ( $comments as $comment ) :
    echo $comment->comment_author . '<br />' . $comment->comment_content;
endforeach;

But that relates to the OOTB comments provided my wordpress. How can we display our new custom fields in this same fashion?

I found this article from 2011 on what I am trying to achieve. WordPress has changed dramatically sense then. Is there a 2020 version of that article for WordPress 5+ ...?

Many thanks!

6
  • did you look into get_comment_meta() - developer.wordpress.org/reference/functions/get_comment_meta – Q Studio Jan 12 at 20:56
  • Did you debug the return value from the function? to a log for example? – Q Studio Jan 12 at 21:04
  • That sounds cool, but I have very little experience with using that. I placed ?><pre><?php var_dump( $fields['source'] ); ?></pre><?php at the bottom of my functions.php file, but the output on my browser window says its null. – klewis Jan 12 at 21:11
  • Can you try: echo get_comment_meta( $comment->comment_ID, 'source', true ); – Q Studio Jan 12 at 21:15
  • Can you check phpmyadmin and look in the comment_meta table for comment meta data matching the comment ID with "source" value? – Q Studio Jan 12 at 21:37
1

Just in case others are stumped with trying to learn how to reveal submitted comments onto a comments page (or any page for this matter), a good starting point to investigate is using the WordPress function wp_list_comments()

There are examples provided on that resource page to get things going in a healthy direction.

I would also include the following debug tactic as a help along the way...

?><pre><?php var_dump( $variable_to_test ); ?></pre><?php

...as mentioned by Q Studio. Thanks for that!

Update

Another good resource to help extend the OOTB comment fields with more fields by WPengineer.com. I've tested it out for myself in 2020, and concepts still work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.