2006
09.19

Comments 的排序

剛剛有人問我怎麼把 comments 的排序顛倒過來( WP 的預設是越晚發表的排在越下面,越早發表的排在越上面) ,但是她希望把早發表的排在下面,把晚發表的排在上面,就像我們一般常見的 WEB 留言板一樣。所以我就翻了一下 WP 的程式看看到底要改哪邊才會有效果。我原本以為 select comment 的敘述應該是放在 theme 裡面,但是後來我發現我想的太單純了,因為如果放在 theme 裡面好像有點不太合乎邏輯。結果, WP 果然不會做不合邏輯的煞情,所以其實那段 SQL 語法是放在 wp-includes 裡面的 comment-functions.php 。

如果要 comments 排序顛倒,那就開啟 comment-function 然後搜尋以下程式碼 (在開頭的地方)

if ( empty($comment_author) ) {
    $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND comment_approved = '1' ORDER BY comment_date DESC"); // DESC 排列
}
else {
    $author_db = $wpdb->escape($comment_author);
    $email_db  = $wpdb->escape($comment_author_email);
    $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND ( comment_approved = '1' OR ( comment_author = '$author_db' AND comment_author_email = '$email_db' AND comment_approved = '0' ) ) ORDER BY comment_date DESC"); // DESC 排列
}

但這樣改有個問題,就是以後每次 UPDATE 都得手動修改這個檔案 SQL 語法,呵呵。

所以其實我不太愛改除了 wp-content/ 目錄之外的檔案,因為每次升級我又得再改一次,有點麻煩是也 :P

1 comment so far

Add Your Comment
  1. 如果真的不改程式碼的話,就必需要改 wp-content/themes/default/comments.php 裡將 comments 給 rsort 如果該模板有自行實作 comments.php 的話,則更該其模板自有的 comments.php
    大部份就在 if($comments) 後面加上 rsort($comments); 就會反相了。
    ps. 沒效率的作法,還是直接交給 mysql 作就好了。

:D :-) :( :o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen:

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>