Retrieve comments from current post using SQL

I am trying to use this code below to auto-refresh comments but at the moment it is displaying all comments. I would like to only show comments for the current post. I am not very experienced with SQL and don’t know how to go about doing this:

<?php
function dp_recent_comments_ajax() {
        $no_comments = 5;
    $comment_len = 300;
        global $wpdb;

    $request = "SELECT * FROM $wpdb->comments";
    $request .= " JOIN $wpdb->posts ON ID = comment_post_ID";
    $request .= " WHERE comment_approved = '1' AND post_status = 'publish' AND post_password =''";
    $request .= " ORDER BY comment_date DESC LIMIT $no_comments";

    $comments = $wpdb->get_results($request);
    if ($comments) {
        foreach ($comments as $comment) {
            ob_start();
            ?>
                <li>
                    <a style="font-size:12px "href="<?php echo get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment->comment_ID; ?>"><?php echo dp_get_author($comment); ?> on <?php echo $comment->comment_date; ?> :</a><br />
                    <span class="recent-comment-text" style="font-size:11px;font-style:italic"><?php echo strip_tags(substr(apply_filters('get_comment_text', $comment->comment_content), 0, $comment_len)); ?>..</span>
                </li>
            <?php
            ob_end_flush();
        }
    } else {
        echo '<li>'.__('No comments', 'my-first-wp-theme').'</li>';
    }
    die(); // this is needed for ajax to work properly
}
function dp_get_author($comment) {
    $author = "";

    if ( empty($comment->comment_author) )
        $author = __('Anonymous', 'my-first-wp-theme');
    else
        $author = $comment->comment_author;

    return $author;
}
add_action('wp_ajax_my_recent_comments', 'dp_recent_comments_ajax');
add_action('wp_ajax_nopriv_my_recent_comments', 'dp_recent_comments_ajax'); //for users that are not logged in

Related posts

Leave a Reply

1 comment

  1. Send your post id in the function and it will look something like this

    <?php
     function dp_recent_comments_ajax($ID) {
        $no_comments = 5;
        $comment_len = 300;
        global $wpdb;
    
    $request = "SELECT * FROM $wpdb->comments";
    $request .= " JOIN $wpdb->posts ON ID = comment_post_ID";
    $request .= " WHERE comment_approved = '1' AND post_status = 'publish' AND post_password =''";
    $request .= " AND ID='{$ID}' ";
    $request .= " ORDER BY comment_date DESC LIMIT $no_comments";