WordPress 預設評論按時間正序顯示 (最舊在前),許多站點希望最新評論優先 (倒序),類似社交媒體體驗。
在主題 comments.php 模板中,評論迴圈前插入一行代碼即可:
comments.php<?php foreach ($comments as $comment) : ?>
<?php $comments = array_reverse($comments, true); ?>
<?php $comments = array_reverse($comments, true); ?>
<?php foreach ($comments as $comment) : ?>
<!-- 評論結構 HTML -->
<?php endforeach; ?>
$comments 是 WP_Comment_Query 返回的 按 comment_date_gmt ASC 排序的對象數組。array_reverse($array, true) 保留鍵值關聯 (true 參數) 將數組順序反轉,變為 DESC (最新在前)。foreach 遍歷即按新順序輸出,不影響 wp_list_comments() 等高級函數內部邏輯 (若主題使用模板標籤而非手寫迴圈,請見下文)。現代主題多使用 wp_list_comments() 而非手寫 foreach,此時需通過 pre_get_comments 鉤子在查詢層面修改排序:
<?php
// functions.php
add_filter('pre_get_comments', function($query) {
if (is_admin() || !$query->is_main_query()) return;
if ($query->query_vars['type'] === 'comment' && isset($query->query_vars['post_id'])) {
$query->query_vars['orderby'] = 'comment_date_gmt';
$query->query_vars['order'] = 'DESC'; // 最新優先
}
});
// functions.php - 完全自定義評論排序
add_filter('comments_array', function($comments, $post_id) {
// $comments 為已按層級構建的樹狀數組
// 此處可實現:優先顯示作者回覆、高讚評論置頂、按嵌套深度排序等
usort($comments, function($a, $b) {
// 例:作者評論優先
$a_author = $a->user_id === get_post_field('post_author', $post_id);
$b_author = $b->user_id === get_post_field('post_author', $post_id);
if ($a_author !== $b_author) return $a_author ? -1 : 1;
return strtotime($b->comment_date_gmt) - strtotime($a->comment_date_gmt);
});
return $comments;
}, 10, 2);