Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How would I make this Function display only the latest 5 comments?

function showLatestComments() {
  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 student perspectives <img src="/wp-content/themes/blue-and-grey/images/hmepage-tri.png" class="class3" /></h2>
 <ul id="comm">';  
 foreach ($comments as $comment) { 
   $output .= '<li><strong>'. $comment->comment_author . ' said</strong> : "' . strip_tags($comment->com_excerpt). '..."</li>';
   }
 $output .= '</ul>';  
 echo $output;  
}//end function
share|improve this question
add comment

1 Answer

the function you posted is limited to 5 comments which means it should work, but anyway there is no need for a custom SQL query when you can use the native get_comments function

function showLatestComments() {
    $comments = get_comments(array(
        'status' => 'approve',
        'number' => '5'
        )
    );
    $output .= '<h2>Latest student perspectives <img src="/wp-content/themes/blue-and-grey/images/hmepage-tri.png" class="class3" /></h2>
    <ul id="comm">';  
    foreach ($comments as $comment) { 
        $output .= '<li><strong>'. $comment->comment_author . ' said</strong> : "' . substr(strip_tags($comment->content),0,99). '..."</li>';
    }
    $output .= '</ul>';  
    echo $output;  
}//end function
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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