• In a function I have a call to the $wpdb:

    global $wpdb;
    	 $sql = "
    	   SELECT DISTINCT comment_post_ID, comment_author, comment_date_gmt, comment_approved, SUBSTRING(comment_content,1,100) AS com_excerpt
    	   FROM $wpdb->comments
    	   WHERE comment_approved = '1'
    	   ORDER BY comment_date_gmt DESC
    	   LIMIT 5";
    	 $comments = $wpdb->get_results($sql);
    	 $output .= '<h2>latest comments</h2><ul id="comm">';
    	 foreach ($comments as $comment) {
    	   $output .= '<li><strong>'. $comment->comment_author . ' said</strong> : "' . strip_tags($comment->com_excerpt). '..."</li>';
    	   }
    	 $output .= '</ul>';

    I want to add to only select comments from the current post though. I feel like I’ve tried everything to define the post_id and the comment_post_id. Any suggestions?

Viewing 1 replies (of 1 total)
  • Is this code within the Loop so that the post ID is available? If so, you can get the comments for the current post like this:

    $sql = "
       SELECT DISTINCT comment_post_ID, comment_author, comment_date_gmt, comment_approved, SUBSTRING(comment_content,1,100) AS com_excerpt
       FROM $wpdb->comments
       WHERE comment_approved = '1'
       AND comment_post_ID = $post->ID
       ORDER BY comment_date_gmt DESC
       LIMIT 5";
Viewing 1 replies (of 1 total)
  • The topic ‘Using variables in SQL $wpdb query’ is closed to new replies.