Clicky

Changing Number of Comments in Recent Comments Block | suksit dot com

Changing Number of Comments in Recent Comments Block

ปัญหาที่ผู้ใช้ Drupal หลายๆ คนน่าจะเคยเจอ คือ จำนวนคอมเมนต์ในบล็อค Recent Comments ที่โมดูล Comment กำหนดมาให้ มันมากหรือน้อยเกินไป คือโดยปกติจะแสดง 10 คอมเมนต์ล่าสุดเสมอ

โชคดีที่การ query และแสดงผลข้อมูลในบล็อค Recent comments ของโมดูล Comment ทำผ่านฟังก์ชัน theme_comment_block() ทำให้เราสามารถแก้ไขจำนวนคอมเมนต์ที่ต้องการให้แสดงในบล็อคด้วยการ override theme function ได้ โดยไม่ต้องแก้ไขโค้ดในโมดูล Comment แต่อย่างใด

วิธีที่น่าจะง่ายที่สุดคือ การแก้ไขไฟล์ template.php ของธีมที่เราใช้งานอยู่ โดยเราจะเพิ่มฟังก์ชัน phptemplate_comment_block() เข้าไปในไฟล์ดังกล่าว ถ้าในธีมที่ใช้ไม่มีไฟล์ template.php ให้สร้างเป็นไฟล์ใหม่ขึ้นมาได้เลย จากนั้นเพิ่มข้อมูลดังนี้

/**
 * Returns a formatted list of 5 recent comments to be displayed in the comment block.
 *
 * Override the default number of 10 recent comments
 * and display only 5 recent comments.
 */
function phptemplate_comment_block() {
  $items = array();
  foreach (comment_get_recent(5) as $comment) {
    $items[] = l($comment->subject, 'node/'. $comment->nid, array('fragment' => 'comment-'. $comment->cid)) .'<br />'. t('@time ago', array('@time' => format_interval(time() - $comment->timestamp)));
  }
  if ($items) {
    return theme('item_list', $items);
  }
}

ตัวโค้ดนั้นผมคัดลอกมาจากไฟล์ comment.module ตรงๆ ส่วนที่แตกต่างกันมีเพียงชื่อฟังก์ชัน ที่เปลี่ยนจาก theme_comment_block() เป็น phptemplate_comment_block() และตรงบรรทัด foreach ที่มีการใส่ parameter ให้ฟังก์ชัน comment_get_recent() เป็นจำนวนคอมเมนต์ที่ต้องการ เนื่องจากถ้าไม่ใส่ parameter ฟังก์ชันนี้จะ default จำนวนคอมเมนต์เป็น 10 นั่นเอง (ดูโค้ดได้ในไฟล์ comment.module)

เนื่องจากเราเพิ่มฟังก์ชันใหม่ในไฟล์ template.php จึงต้องทำการ rebuild theme registry เพื่อให้ Drupal รู้จักฟังก์ชันนี้ก่อน โดยไปที่หน้า /admin/build/modules หนึ่งรอบ จากนั้นค่อยโหลดหน้าเว็บเพจใหม่

แน่นอนว่าเราสามารถ override การแสดงผลของบล็อค Recent comments โดยใช้วิธีอื่น เช่น การสร้างไฟล์ .tpl.php ซึ่งทำได้โดยใช้หลักการใกล้เคียงกัน ทั้งนี้ก็ขึ้นอยู่กับความต้องการใช้งาน และความสะดวกในการ maintain โค้ดของแต่ละคนครับ

2 comments

landsesseBoop's picture
landsesseBoop (visitor) says:

Hello. And Bye.

ปลวก's picture
ปลวก (visitor) says:

ขอบคุณครับ กำลังเล่น Drupal อยู่เหมือนกัน ยังไม่ชำนาญ ขอความรู้เรื่อยๆครับ

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.