ARCHIVE /
[Drupal] 隨機顯示最新內容
案例:在最新的五則內容中,隨機顯示其中三則內容。
做法:
- 用 Views 先建立顯示五則內容的 display(如 block);注意,因為是要顯示最新的五則內容,所以 Items per page 要設為「5」,而 sort criteria 要設以「發表日期」排序(desc)
- 寫一個客製模組,然後利用 hook_views_post_execute 函式來重寫輸出結果,程式碼如下
if ($view->name == 'view_name' && $view->current_display == 'display_name') {
$rand = array_rand($view->result, 3);
foreach ($rand as $key => $value) {
$result[] = $view->result[$value];
}
$view->result = $result;
}
說明:透過 array_rand 函式,只能取得 array key,而不是取得整個 views 的結果,因此還要利用迴圈依序取出 views 的結果並暫存到某個變數,最後再將結果覆蓋回 views 的結果。
如果是只需要從五則近期內容隨機取出一則,就不用這麼複雜,只需要在 hook_views_post_execute 函式中寫入下面這行程式碼即可
$view->result = array($view->result[array_rand($view->result)]);
參考資料:[SOLVED] Randomly display content of one of the first five nodes in the query in a Views block.