2

So I've been trying for a hour or so now to list comment by it's ID. I've tried the get_comment($id, $output) function but it didn't work well, so I went back to whatever is shown below, but it just shows all comments. I want it to show just one comment by it's ID. I can't figure out a way to do it. What am I doing wrong?

$args = array(
    'id' => 1,
);

// The Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );

// Comment Loop
if ( $comments ) {
    foreach ( $comments as $comment ) {
        echo '<p>'.$comment->comment_content.'</p>';
    }
}
1

The Codex makes it seem like you can query for a specific comment by ID, as does the GenerateWP query generator, but I couldn't get it to work with either of those examples. Even looking through the WP_Comment_Query:query() code makes it clear that you should be able to pass the ID in the parameters.

That said, using get_comment() is your only way to go for now. Here's what can work based on your original code:

<?php
/**
 * Get the contents of a single comment by its ID.
 * 
 * @param  int $comment_id The ID of the comment to retrieve.
 * 
 * @return string The comment as a string, if present; null if no comment exists.
 */
function wpse120039_get_comment_by_id( $comment_id ) {
    $comment = get_comment( intval( $comment_id ) );

    if ( ! empty( $comment ) ) {
        return $comment->comment_content;
    } else {
        return '';
    }
}

echo '<p>' . wpse120039_get_comment_by_id( '34' ) . '</p>';
  • Thanks, it worked like a charm once placed into the functions.php file. Is there a specific reason to use the wpse120039 in the front of the function or can I delete it. – Matthew Abrman Jan 16 '14 at 20:28
  • Glad it worked! The prefix is just there so it doesn't conflict with any other function that may have the same name. I've been bitten by that before, so now I tend to prefix functions I put here with the question number. – Morgan Estes Jan 16 '14 at 20:32
  • 1
    Morgan, the only thing I'd add to that is a check to see if the $comment is valid before returning (to avoid an error message). – Christopher Ross Jan 16 '14 at 21:50
  • @ChristopherRoss Good idea. I've updated my code to check for a valid $comment, plus typecast the param into an int up front. – Morgan Estes Jan 16 '14 at 22:06
0

I don't see an argument to WP_Comment_Query that would let you search comments by comment ID, just by the associated post ID. However, get_comment will do it. An example from the Codex:

$my_id = 7;
$comment_id_7 = get_comment( $my_id ); 
$name = $comment_id_7->comment_author;

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.