สำหรับบทความนี้มาจากผมได้พัฒนาโปรเจ็คหนึ่งครับ เป็นโปรเจ็คที่ต้องมีการ customize wordpress ค่อนข้างเยอะมากๆ และหนึ่งในนั้นก็คือการแสดงผลว่า ในหมวดหมุ่นี้ มีคนมาคอมเมนต์เท่าไหร่ โดยที่จะเปลี่ยนไปอัตโนมัตเมื่อคลิกไปยังแต่ละหมวดหมู่ ตอนแรกผมก็นั่งคิดขั้นตอนการทำอยู่ครับ ว่าจะสร้างอัลกอริธึมยังไงดีนะ พยายามค้นคว้าหาข้อมูลทั้งวันก็ไม่เจอ หาโน่นหานี่ จนในที่สุดก็คิดออกครับ ฮ่าๆ
อัลกอริธึมที่จะทำสร้างก็คือ อย่างแรกต้องทราบก่อนว่า หมวดหมู่นั้นมีไอดีว่าอะไร?
จากนั้นก็หาวิธีการคิวรี่คอมเมนต์ที่อยู่ในไอดีนั้นครับ พอคิวรี่ได้แล้ว ผมก็เอามาหาจำนวนที่คิวรี่ได้ ในที่สุดก็ได้ตามโค้ดนี้มาครับ
[codesyntax lang=”php”]
<?php
$cat = get_query_var('cat');
$number=0;
// Posts per page setting
$ppp = get_option(''); // either use the WordPress global Posts per page setting or set a custom one like $ppp = 10;
$custom_offset = 0; // If you are dealing with your custom pagination, then you can calculate the value of this offset using a formula
// category (can be a parent category)
$category_parent = $cat;
// lets fetch sub categories of this category and build an array
$categories = get_terms( 'category', array( 'child_of' => $category_parent, 'hide_empty' => false ) );
$category_list = array( $category_parent );
foreach( $categories as $term ) {
$category_list[] = (int) $term->term_id;
}
// fetch posts in all those categories
$posts = get_objects_in_term( $category_list, 'category' );
$sql = "SELECT comment_ID, comment_date, comment_content, comment_post_ID
FROM {$wpdb->comments} WHERE
comment_post_ID in (".implode(',', $posts).") AND comment_approved = 1
ORDER by comment_date DESC";
$comments_list = $wpdb->get_results( $sql );
$comment_count=count($comments_list);
if($comment_count<10){
echo "00".$comment_count;
}
elseif($comment_count<100){
echo "0".$comment_count;
}
else{
echo $comment_count;
}
?>
[/codesyntax]
สำหรับโค้ดนี้ไม่ได้เขียนเองทั้งหมดนะครับ พยายามหาใน Google นั่งดัดแปลง เอาโน่นแปะนี่ ลองหลายวิธี จนในที่สุดก็ได้ผลลัพธ์ตามที่ต้องการครับ เลยเอามาแชร์เผื่อใครมีโปรเจ็คแนวๆนี้ ก็นำไปใช้ได้นะครับ
ขอบคุณ References
http://codex.wordpress.org/Class_Reference/wpdb
http://blog.ashfame.com/2011/04/get-comments-category-wordpress/




